-3

I have got an object with two arrays:

{
    names: ["aa", "bb", "cc", "dd", "ee", "ff"],
    price: [3,6,2,7,1,9]
}

I need to sort price but also I need that names also to be sorted.

{
    names: ["ee", "cc", "aa", "bb", "dd", "ff"],
    price: [1,2,3,6,7,9]
}
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145

2 Answers2

1

const input = {
    names: ["aa", "bb", "cc", "dd", "ee", "ff"],
    price: [3,6,2,7,1,9]
}

const merged_ary = []
for(var i = 0; i < input.names.length; i ++) {
  merged_ary.push({
    names: input.names[i],
    price: input.price[i],
  });
}

merged_ary.sort((a, b) => a.price - b.price)

const output = merged_ary.reduce((arr, val) => {
  if (!arr.names) arr.names = []
  if (!arr.price) arr.price = []
  arr.names.push(val.names);
  arr.price.push(val.price);
  return arr;
}, {});

console.log(output);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

I have done it like this

let obj = 
{
    names: ["aa", "bb", "cc", "dd", "ee", "ff"],
    price: [3,6,2,7,1,9]
}

function sortCorres(obj) {
   let acc = {}
   obj.price.forEach((price, i) => {
     acc[price] = obj.names[i]
   })
   obj.price.sort((a,b) => a - b)
   obj.names = obj.price.map(price => acc[price])
   return obj;
}

sortCorres(obj)

console.log(obj);
bill.gates
  • 14,145
  • 3
  • 19
  • 47