2 回答
TA贡献1816条经验 获得超6个赞
let arr = getData();
arr.sort(function(a, b) {
if( a.lineNum === b.lineNum ) {
return a.item - b.item;
} else {
return a.lineNum - b.lineNum;
}
});
// return a.lineNum === b.lineNum ? a.item - b.item : a.lineNum - b.lineNum;
for( let i = 0; i < arr.length; i++ ) {
if( arr[i].lineNum > 0 ) break;
arr[i].linePosition = i;
}
// Used classic loop, to break it and avoid unnecessary iterations.
console.log( JSON.stringify(arr).replace(/\},/g, "},\n") );
/***/
function getData() {
return [
{id: 11, item: 132, lineNum: 4, linePosition: 5},
{id: 2, item: 124, lineNum: 0, linePosition: 2},
{id: 9, item: 130, lineNum: 0, linePosition: 5},
{id: 12, item: 133, lineNum: 1, linePosition: 3},
{id: 15, item: 136, lineNum: 3, linePosition: 2},
{id: 13, item: 134, lineNum: 0, linePosition: 4},
{id: 10, item: 131, lineNum: 2, linePosition: 1},
{id: 8, item: 129, lineNum: 3, linePosition: 3},
{id: 1, item: 123, lineNum: 0, linePosition: 5},
{id: 3, item: 125, lineNum: 1, linePosition: 7},
{id: 5, item: 127, lineNum: 0, linePosition: 9},
{id: 7, item: 128, lineNum: 1, linePosition: 2},
{id: 4, item: 126, lineNum: 0, linePosition: 4},
{id: 14, item: 135, lineNum: 3, linePosition: 9},
];
}
.as-console-wrapper { max-height: 100vh !important; }
TA贡献1812条经验 获得超5个赞
您可以使用 Javascript.sort()函数完成上述任务。它可以采用可选的比较函数参数,该参数指定定义排序顺序的函数。
let arr = [
{id: 11, item: 132, lineNum: 4, linePosition: 5},
{id: 2, item: 124, lineNum: 0, linePosition: 2},
{id: 9, item: 130, lineNum: 0, linePosition: 5},
{id: 12, item: 133, lineNum: 1, linePosition: 3},
{id: 15, item: 136, lineNum: 3, linePosition: 2},
{id: 13, item: 134, lineNum: 0, linePosition: 4},
{id: 10, item: 131, lineNum: 2, linePosition: 1},
{id: 8, item: 129, lineNum: 3, linePosition: 3},
{id: 1, item: 123, lineNum: 0, linePosition: 5},
{id: 3, item: 125, lineNum: 1, linePosition: 7},
{id: 5, item: 127, lineNum: 0, linePosition: 9},
{id: 7, item: 128, lineNum: 1, linePosition: 2},
{id: 4, item: 126, lineNum: 0, linePosition: 4},
{id: 14, item: 135, lineNum: 3, linePosition: 9}
];
//sorting the given array, first based on lineNum, then by item
arr.sort(function(a,b){
if(a.lineNum !== b.lineNum)
return a.lineNum - b.lineNum;
return a.item - b.item;
});
// modify each object where lineNum===0, linePosition starting from 0
// since we have sorted, break when first lineNum > 0
let linePos = 0;
for( let i = 0; i < arr.length; i++ ) {
if( arr[i].lineNum > 0 )
break;
if(arr[i].lineNum === 0)
arr[i].linePosition = linePos++;
}
// console.log(arr); //<-- This prints as array
console.log( JSON.stringify(arr).replace(/\},/g, "},\n") ); // <-- This prints your mentioned format
添加回答
举报