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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.