I have this array -
let array = [
{
"id": 123,
"pair": 312
},
{
"id": 321,
"pair": 111
},
{
"id": 312,
"pair": 123
},
{
"id": 111,
"pair": 321
}
];
And i need it to be sorted like this =
let array = [
{
"id": 123,
"pair": 312
},
{
"id": 312,
"pair": 123
},
{
"id": 321,
"pair": 111
},
{
"id": 111,
"pair": 321
}
];
Which means that i need to find the matched value of the pair key in the object, and put it right after the first element (eventually i need the to be sorted in pairs order - of course the array will be way bigger and mixed) i could not find a efficient way to achieve this.
this is what i tried - it feels very unefficient
products is the array i get from the server.
let pairs = [];
let prods = [...products];
for(let product of prods){
if(product.matched){
continue;
}
let pairStock = product.pairStock;
let companyId = product.company;
let matched = prods.filter(prod => prod.productId === pairStock && String(prod.company) === String(companyId));
if(matched.length > 0){
pairs.push(product);
pairs.push(matched[0]);
let index = prods.findIndex(prod => prod.productId === matched[0].productId);
prods[index].matched = true;
}
};