javascript - 循环遍历数组时排名 javascript

标签 javascript arrays

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/

相关文章:

javascript - JQuery - 将方法分配给变量

php - 从数据库中选择并存储在数组中

java - Arrays.asList() 令人困惑的源代码

c++ - 取消引用一个指向数组类型的结束指针

javascript - 在 JavaScript 中使用摩擦力和动量滚动

javascript - Next() 和 prev() 隐藏和显示 div

javascript - 拉维 Vue.js : Error in render: "TypeError: Cannot read property ' user' of null"

c++ - GCC8.2如何启用警告: array subscript is above array bounds [-Warray-bounds]

arrays - swift : TableView Cell data change with the Button Actions

javascript - jQuery 的 addClass 不添加类