繁体   English   中英

javascript通过属性的存在对对象数组进行排序,同时保持旧顺序

[英]javascript sort array of objects by existence of a property while keeping old order

我有一个包含大约 1,500 个元素的对象数组

var a = [
    {
        'name': 'jug',
        'price': 0,
    },
    {
        'name': 'watermelon',
        'price': 47,
    },
    {
        'name': 'pizza',
        'price': 0,
    },
    {
        'name': 'handkerchief',
        'price': 52,
    },
    ..........................
]

我在获取数据时不断更新价格数组。

我需要重新排序具有价格的元素,并以相同的顺序保留最上面的元素。

如果这还不是很清楚,假设您有一个包含特定订单产品的网页,并且正在批量加载产品的价格。 我想把价格放在最上面,并按这个顺序排列,这样产品就不会跳来跳去。 但是,当我得到价格时,我想在列表中的最后一个价格之后将其推到底部。

尝试

a.sort(function(a,b){ 

  var priceA = a.price? a.price : Number.MAX_SAFE_INTEGER;
  var priceB = b.price? b.price : Number.MAX_SAFE_INTEGER;
  return a.price-b.price;
});

这将确保如果价格不可用,它们将保持在底部。

为了使其工作,您需要有 indexOfObj,它是数组中所需对象的索引:

var updatedElement = a.splice(indexOfObj, 1); // Remove the element with the updated price
a.push(updatedElement); // Add the new element to the end of the 'a' array.

好的,我在这里做一些假设,因为老实说这个问题不是很清楚。 但我相信你想做这样的事情:(假设newprices是一批更新数据)

// if product already in list update price, otherwise insert at bottom
var i, index, newprice;
for(i = 0; i<newprices.length; i++) {
    newprice = newprices[i];
    index = a.findIndex(function(p) { return p.name === newprice.name; });
    if(index > -1) { a[index].price = newprice.price; }
    else { a.push[newprice]; }
}

或者,也许你想做这样的事情:

// put items that get updated prices or are new altogether at the end of the list
var i, index, newprice;
for(i = 0; i<newprices.length; i++) {
    newprice = newprices[i];
    index = a.findIndex(function(p) { return p.name === newprice.name; });
    if(index > -1) { a.splice(index, 1); }
    a.push[newprice];
}

但是,是的,如果您更清楚地说明您要做什么,那肯定会有所帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM