如何让console.table()排序后保留原position作为(index)列?
问题:按quantity排序后保留position作为console.table的索引列
初始代码与输出
初始代码将数组转换为以position为键的对象,console.table输出中(index)列直接显示position值:
const data = [ { position: 28, word: "the", quantity: 10 }, { position: 38, word: "was", quantity: 5 }, { position: 8, word: "age", quantity: 2 }, ]; const transformed = data.reduce((acc, {position, ...x}) => { acc[position] = x; return acc}, {}) console.table(transformed);
输出:
┌─────────┬───────┬──────────┐ │ (index) │ word │ quantity │ ├─────────┼───────┼──────────┤ │ 8 │ 'age' │ 2 │ │ 28 │ 'the' │ 10 │ │ 38 │ 'was' │ 5 │ └─────────┴───────┴──────────┘
添加排序后的问题
尝试按quantity降序排序时,转换为数组导致丢失position索引,(index)列变为数组下标:
const data = [ { position: 28, word: "the", quantity: 10 }, { position: 38, word: "was", quantity: 5 }, { position: 8, word: "age", quantity: 2 }, ]; const transformed = data.reduce((acc, {position, ...x}) => { acc[position] = x; return acc}, {}) const transformedArray = Object.values(transformed).sort((a, b) => b.quantity - a.quantity); console.table(transformedArray);
输出:
┌─────────┬───────┬──────────┐ │ (index) │ word │ quantity │ ├─────────┼───────┼──────────┤ │ 0 │ 'the' │ 10 │ │ 1 │ 'was' │ 5 │ │ 2 │ 'age' │ 2 │ └─────────┴───────┴──────────┘
期望输出
希望排序后仍保留position作为(index)列的值,输出如下:
┌─────────┬───────┬──────────┐ │ (index) │ word │ quantity │ ├─────────┼───────┼──────────┤ │ 28 │ 'the' │ 10 │ │ 38 │ 'was' │ 5 │ │ 8 │ 'age' │ 2 │ └─────────┴───────┴──────────┘
已知备选方案
可以额外保留position列,但这不是优先选择:
┌─────────┬──────────┬───────┬──────────┐ │ (index) │ position │ word │ quantity │ ├─────────┼──────────┼───────┼──────────┤ │ 0 │ 28 │ 'the' │ 10 │ │ 1 │ 38 │ 'was' │ 5 │ │ 2 │ 8 │ 'age' │ 2 │ └─────────┴──────────┴───────┴──────────┘
解决方案
利用现代JavaScript对象保留插入顺序的特性,先对原数组按quantity降序排序,再构建以position为键的对象:
const data = [ { position: 28, word: "the", quantity: 10 }, { position: 38, word: "was", quantity: 5 }, { position: 8, word: "age", quantity: 2 }, ]; // 先按quantity降序排序原数组 const sortedData = [...data].sort((a, b) => b.quantity - a.quantity); // 构建以position为键的对象,保留排序后的顺序 const transformed = sortedData.reduce((acc, { position, ...x }) => { acc[position] = x; return acc; }, {}); console.table(transformed);
此时console.table的输出会完全符合期望:(index)列显示position值,同时按quantity降序排列。
内容的提问来源于stack exchange,提问作者Bruno Machado
相关产品推荐
相关产品推荐

