I need to sort an array of objects. How can I sort this array based on key arrval[index]?
arr = [
{ id: 0, name: 'Name 1', arrval: [5, 3, 1] },
{ id: 1, name: 'Name 2', arrval: [6, 4, 3] },
{ id: 2, name: 'Name 3', arrval: [3, 2, 0] },
]
So if I want to sort it by arrval[1], ascending, the result should be:
arr = [
{ id: 2, name: 'Name 3', arrval: [3, 2, 0] },
{ id: 0, name: 'Name 1', arrval: [5, 3, 1] },
{ id: 1, name: 'Name 2', arrval: [6, 4, 3] },
]
I can already sort this if I sort it by id or name but I can't seem to make it work by arrval
5 Answers 5
Simple as that
const src = [
{ id: 0, name: 'Name 1', arrval: [5, 3, 1] },
{ id: 1, name: 'Name 2', arrval: [6, 4, 3] },
{ id: 2, name: 'Name 3', arrval: [3, 2, 0] },
]
const sortByKeyIdx = ([...arr], key, idx) =>
arr
.sort(({[key]:a}, {[key]:b}) =>
a[idx]-b[idx])
console.log(sortByKeyIdx(src, 'arrval', 1))
Comments
Just sort by arrval like you sort by id or name
arr.sort( (a, b) => a.arrval[0] - b.arrval[0] )
Comments
Just pass the arrval index and sort it like you normally would. You can try this solution:
const sort = index => {
const arr = [
{ id: 0, name: 'Name 1', arrval: [5, 3, 1] },
{ id: 1, name: 'Name 2', arrval: [6, 4, 3] },
{ id: 2, name: 'Name 3', arrval: [3, 2, 0] }
]
return arr.sort((x, y) => x.arrval[index] - y.arrval[index])
}
console.log(sort(2))
Comments
There is two way to do this
first:
let arr = [{
id: 0,
name: 'Name 1',
arrval: [5, 3, 1]
},
{
id: 1,
name: 'Name 2',
arrval: [6, 4, 3]
},
{
id: 2,
name: 'Name 3',
arrval: [3, 2, 0]
},
]
let index = 1
arr.sort((a, b) => {
if (a.arrval[index] < b.arrval[index]) return -1
else if (a.arrval[index] < b.arrval[index]) return 1
else return 0
})
console.log(arr)
second:
let arr = [{
id: 0,
name: 'Name 1',
arrval: [5, 3, 1]
},
{
id: 1,
name: 'Name 2',
arrval: [6, 4, 3]
},
{
id: 2,
name: 'Name 3',
arrval: [3, 2, 0]
},
]
let index = 1
arr.sort((a, b) => a.arrval[1] - b.arrval[1])
console.log(arr)
Comments
The accepted answer sorts by the first array value. If you need to be able to deal with ties, where then the second array value becomes decisive, ...etc, then use this:
const src = [
{ id: 0, name: 'Name 1', arrval: [5, 3, 3] },
{ id: 1, name: 'Name 2', arrval: [5, 3, 1] },
{ id: 2, name: 'Name 3', arrval: [5, 2, 0, 1] },
{ id: 3, name: 'Name 4', arrval: [5, 2, 0] },
]
src.sort(({arrval: a}, {arrval: b}) => {
for (let i = 0, len = Math.min(a.length, b.length); i < len; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return a.length - b.length;
});
console.log(src);
idorname, what prevents you doing the same for the first index ofarrval?idandname.arr.sort((a, b) => a.arrval[0] - b.arrval[0])