var testArray = [{
value: john,
count: 5
},
{
value: henry,
count: 2
},
{
value: bill,
count: 10
}]
testArray.map(function(value) {
//otherfunctions
})
所以我有一个函数,我已经通过类似于上面的对象数组进行映射。我想根据计数向排名对象添加第三个值。 我当前的想法是完成我已经在做的 map ,然后根据计数对数据重新排序,然后根据数组中的排序位置分配排名。但这似乎很冗长,因为我已经映射了数组?
最佳答案
普通 JS:
var testArray = [{
value: john,
count: 5
},
{
value: henry,
count: 2
},
{
value: bill,
count: 10
}]
let newArray = testArray.map(function(item) {
return {
value: item.value,
count: item.count,
newProperty: 'x'
}
}).sort(function(x, z) {
return x.count - z.count;
});
ES6:
let newArray = testArray
.map(item => {
return {
...item,
newProperty: 'x'
}
}).sort((x, z) => x.count - z.count);
附注这是进行此计算的函数式方法,应该有一个 o(n*nlog n) 时间,您可以使用命令式方法在 o(n) 中完成它,但在我看来,这更容易阅读/理解。
编辑 1 在作者评论后:想要将当前计数添加到项目中(无法想到有必要这样做的情况),但只是为了沉迷:
let newArray = testArray
.map((item, index) => {
return {
...item,
currentCount: index
}
}).sort((x, z) => x.count - z.count);
了解更多关于map的信息
关于javascript - 循环遍历数组时排名 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968129/