关于javascript:JavaScript-ES6实现一个对象数组按照另一个对象数组进行排序

8次阅读

共计 902 个字符,预计需要花费 3 分钟才能阅读完成。

借助此篇博客,实现了须要的性能,特此记录一下:https://www.cnblogs.com/guojbing/p/10872867.html

假如有一个对象数组:

const arr1 = [{buyerId: "1", name: "WW"},
    {buyerId: "2", name: "RR"},
    {buyerId: "3", name: "OO"},
    {buyerId: "4", name: "ll"},
    {buyerId: "5", name: "DD"},
    {buyerId: "6", name: "SS"}
]

另一对象数组为:

const arr2 = [{buyerId: "4", totalPrice: "7.00"},
    {buyerId: "3", totalPrice: "90.00"},
    {buyerId: "2", totalPrice: "10.00"},
    {buyerId: "6", totalPrice: "70.00"},
    {buyerId: "1", totalPrice: "9.00"},
    {buyerId: "5", totalPrice: "60.00"}
]

当初心愿 arr2 依照 arr 的 buyerId 属性排序,并显示其价格。应该怎么做呢?
首先,提取出 arr1 中的 buyerId 到一个新的数组:

let curArr = [];
arr1.find(item => {curArr.push(item.buyerId)
});

这样就获取到了数组:

接着,让 arr2 依照 curArr 的数据排放顺序排列:

let newArr = [];
arr2.sort((a, b) => {const prev = curArr.indexOf(a.buyerId);
    const next = curArr.indexOf(b.buyerId);
    return prev-next;
});
arr2.forEach(item => {newArr.push(item)
})

失去的后果为:

这样就失去了依照要求排列的新数组,如果要只显示价格,就把 newArr 数组中的 totalPrice 提取到新的数组中,即可显示。

以上,就是我想要分享给大家的,还有另一种简略点的,对象数组依据数组进行比拟的排序形式,具体的请看文章开始贴出的博客地址。

正文完
 0