简体   繁体   English

通过查看另一个数组顺序对对象数组进行排序

[英]Sort object array by looking at another array order

I'm trying to sort an object array by looking at another arrays order, my first array is something like this 我试图通过查看另一个数组顺序来排序对象数组,我的第一个数组是这样的

["HV001O3XL", "HV001OSML", "HV001OLGE"]

and my object array is like : 和我的对象数组是这样的:

[{productcode: "HV001OSML", price: 6, qty: "2", desc: "HV001 WAISTCOAT ORN", stock: "138"},{productcode: "HV001OLGE", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "271"},{productcode: "HV001O3XL", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "1112"}]

I would like to re-shuffle the object array so that the object.productcode matched the first array, HV001O3XL being first instead of HV001OSML etc. Is this possible in angular or javascript? 我想重新调整对象数组的位置,以便使object.productcode与第一个数组匹配,HV001O3XL首先而不是HV001OSML等。这可能是用angular或javascript吗?

 const objs = [ { productcode: "HV001OSML", price: 6, qty: "2", desc: "HV001 WAISTCOAT ORN", stock: "138" }, { productcode: "HV001OLGE", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "271" }, { productcode: "HV001O3XL", price: 6, qty: "1", desc: "HV001 WAISTCOAT ORN", stock: "1112" } ]; const result = [ "HV001O3XL", "HV001OSML", "HV001OLGE" ].map((key) => objs.find(item => item.productcode === key)); console.log(result); 

const orders = ['a', 'b', 'c', 'd']; let objects = [{ code: 'd' }, { code: 'c' }, { code: 'a', }, { code: 'b' }] objects.sort((a, b) => orders.indexOf(a.code) - orders.indexOf(b.code)); console.log(objects);

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

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