简体   繁体   中英

sort an array of object accoring to the values

I have this array of objects:

const array =[ 
  { a: 'good car' },
  { a: 'good car1' },
  { a: 'good car2' },
  { a: 'good car3' },
  { a: 'good car4' },
  { b: 'good car1' } 
];

I need to sort it via values except in the case of ties. In the case of ties, the key is used to break the tie. I searched A LOT but couldn't use the answers as my keys in objects are not the same and also in case of the tie (values are the same), I cannot handle that. Any suggestions?

You could get the entries, pick the first one and destructure it to key and value and take the same for the other object, then return the chained sorting values.

 var array = [{ v21: 'sad sdd' }, { aaa: 'sad sdd' }, { v11: 'r err rr' }, { hf32: 'erwwer fgh' }, { z3f2: 'agfrr vbbar' }, { t142: 'gggoog anfa' }, { u23: 'fa handle err' }]; array.sort((a, b) => { var [keyA, valueA] = Object.entries(a)[0], [keyB, valueB] = Object.entries(b)[0]; return valueA.localeCompare(valueB) || keyA.localeCompare(keyB); }); console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

use sort from es6.

try this code:

const array =[ 
  { v21: 'sad sdd' },
  { v11: 'r err rr' },
  { hf32: 'erwwer fgh' },
  { z3f2: 'agfrr vbbar' },
  { t142: 'agfrr vbbar' },
  { u23: 'fa handle err' } 
]

array.sort( (x,y) => { 
  if ( Object.values(x)[0] > Object.values(y)[0] )
    return 1
  else if ( Object.values(x)[0] < Object.values(y)[0] )
    return -1
  else {
    if ( Object.keys(x)[0] > Object.keys(y)[0] )
      return 1
    else if ( Object.keys(x)[0] < Object.keys(y)[0] )
      return -1
  }
})

You can try the following code:

 const array =[ { v21: 'sad sdd' }, { v11: 'r err rr' }, { hf32: 'erwwer fgh' }, { z3f2: 'agfrr vbbar' }, { z3f1: 'agfrr vbbar' }, { t142: 'gggoog anfa' }, { u23: 'fa handle err' } ]; array.sort((a,b) => { if (a[Object.keys(a)[0]] === b[Object.keys(b)[0]]) { return Object.keys(a)[0].localeCompare(Object.keys(b)[0]); } return a[Object.keys(a)[0]].localeCompare(b[Object.keys(b)[0]]); }); console.log(array); 

A variant without using compare function:

const array = [
  { v21: "sad sdd" },
  { v11: "r err rr" },
  { hf32: "erwwer fgh" },
  { z3f2: "sad sdd" },
  { t142: "gggoog  anfa" },
  { u23: "fa handle err" }
];

const result = array
  .map(item => ({
    key: Object.keys(item)[0],
    value: item[Object.keys(item)[0]]
  }))
  .map(item => `${item.value}:${item.key}`)
  .sort()
  .map(item => item.split(":"))
  .map(item => ({ [item[1]]: item[0] }));

console.log(result);

have to use maybe some other join char instead of ':' if it is expected in the value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM