0

I have data in javascript from ajax like below.

data:{site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"]}

I want sort the data by month.

result I want:

data: {site: ["def", "abc", "gfr"], month: ["2", "3", "6"], value: ["21", "10", "1"]}

I know I can sort array like data.month.sort() but it sorts only month array. How do I sort all of values by one key's value?

georg
  • 211,518
  • 52
  • 313
  • 390
Eunmi Kong
  • 33
  • 5
  • maybe you'll find your response here : https://stackoverflow.com/questions/11499268/sort-two-arrays-the-same-way – RenaudC5 May 07 '19 at 12:43

3 Answers3

1

A standard method is to take the indices of the key array for sorting and sort the indices as pattern for all other arrays by taking the index and the value from the key array.

At the end map the soretd array to the properties.

var data = { site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"] },
    array = data.month,
    indices = [...array.keys()].sort((a, b) => array[a] - array[b]);

Object.keys(data).forEach(k => data[k] = indices.map(i => data[k][i]));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You could sort the month's keys (indices) based on their numerical value first. Then use map to get the data specific index for each of the array:

This sorts the month based on their numerical value

const data = {site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"]}

const { site, month, value } = data;

const keys = [...month.keys()].sort((a,b) => month[a] - month[b])

const output = { 
  site: keys.map(k => site[k]),
  month: keys.map(k => month[k]),
  value: keys.map(k => value[k]),
}

console.log(output)
adiga
  • 34,372
  • 9
  • 61
  • 83
0

another way to do it would be (considering site is the key):

const data = {site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"]}

const output = data.site
   .map((s,i)=> ({site:s, month: data.month[i], value: data.value[i]}))
   .sort((a, b) => b.value - a.value)
   .reduce((acc,cur) => ({
         site:[...acc.site, cur.site],
         month:[...acc.month, cur.month], 
         value:[...acc.value, cur.value]
      }),
      {site:[],month:[], value:[]});

console.log(output)
adiga
  • 34,372
  • 9
  • 61
  • 83
Romain
  • 812
  • 6
  • 8