james
james

Reputation: 570

how to sort an array of objects with different keys

I'm trying to sort an array of objects by a key in a particular position. The only problem is that each object has a different key name.

here is an example of an object i'm trying to sort:

let data = [
  {name: "James", x: 3, }, 
  {name: "Thomas", y: 1}, 
  {name: "Zack", z: 2}
];

I'm trying to sort it by the 2nd key so the order should be

    [
      {name: "James", x: 3, }, 
      {name: "Zack", z: 2},
      {name: "Thomas", y: 1} 
    ];

here is how I'm trying to do it:

let data = [
      {name: "James", x: 3, }, 
      {name: "Thomas", y: 1}, 
      {name: "Zack", z: 2}
    ];

data.sort((a, b) => {
  let key1 = Object.keys(a)[1];
  let key2 = Object.keys(b)[1];
  return a[key1] > b[key2]
  });
console.log(data)

Here is my jsbin

https://jsbin.com/lihefodoni/edit?html,js,console

Not sure why it's not working. I'm trying to do this in my react Application so I don't know if there's something different I need to do?

Upvotes: 0

Views: 116

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386550

You could exclude the unwanted key and take the values of the object. it works by taking the only item without index.

let data = [{ name: "James", x: 3 }, { name: "Thomas", y: 1 }, { name: "Zack", z: 2 }];

data.sort(({ name, ...a }, { name: _, ...b }) => Object.values(b) - Object.values(a));

console.log(data)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Snow
Snow

Reputation: 4097

The .sort callback expects a number as a return value, not a Boolean (as the < operator will evaluate to). Return the numeric difference instead:

let data = [
      {name: "James", x: 3, }, 
      {name: "Thomas", y: 1}, 
      {name: "Zack", z: 2}
    ];

data.sort((a, b) => {
  let key1 = Object.keys(a)[1];
  let key2 = Object.keys(b)[1];
  return b[key2] - a[key1]
});
console.log(data)

To make sorting more reliable, .find the entry whose key is not name:

let data = [
      {name: "James", x: 3, }, 
      {name: "Thomas", y: 1}, 
      {name: "Zack", z: 2}
    ];

data.sort((a, b) => {
  const aEntry = Object.entries(a).find(([key]) => key !== 'name');
  const bEntry = Object.entries(b).find(([key]) => key !== 'name');
  return bEntry[1] - aEntry[1];
});
console.log(data)

Upvotes: 6

Related Questions