1

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?

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

The only issue with this is that it adds the same object twice so it ends up [{productcode: "HV001OLGE", price: 6, qty: "2", desc: "HV001 WAISTCOAT ORN", stock: "271"},{productcode: "HV001OLGE", price: 6, qty: "2", desc: "HV001 WAISTCOAT ORN", stock: "271"}]
@GazSmith If you run this code here, it don't create doubles.
1
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.