借助此篇博客,实现了须要的性能,特此记录一下: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提取到新的数组中,即可显示。
以上,就是我想要分享给大家的,还有另一种简略点的,对象数组依据数组进行比拟的排序形式,具体的请看文章开始贴出的博客地址。