Gaz Smith
Gaz Smith

Reputation: 1108

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?

Upvotes: 1

Views: 48

Answers (2)

Big Bad Waffle
Big Bad Waffle

Reputation: 404

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);

Upvotes: 1

ponury-kostek
ponury-kostek

Reputation: 8070

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);

Upvotes: 4

Related Questions