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?

1

3 Answers 3

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

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

Comments

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)

Comments

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)

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.