1

I have 2 objects where I want the second one to be in the same order as the first one.

Ex:

const obj1 = [
  { key: 1, id: 1, name: "John" },
  { key: 2, id: 2, name: "Ann" },
  { key: 3, id: 3, name: "Kate" }
];

const obj2 = [
  { key: 2, id: 2, name: "Ann" },
  { key: 1, id: 1, name: "John" },
  { key: 3, id: 3, name: "Kate" }
];

The purpose is to have obj2 in same order as obj1, but only sort with keys. I'm trying to make an helper function which will pass 3 argument:

function helper(obj1, obj2, key) {
  // return new object with sorted array do not modify existing
}

I can sort one of this, but cant combine 2object together

VLAZ
  • 26,331
  • 9
  • 49
  • 67

4 Answers4

0

My idea is to use hash map to store key obj2, then loop through key obj1 to sort obj2

 const obj1 = [
    {key: 1, id: 5, name: 'John'},
    {key: 2, id: 5, name: 'John'},
    {key: 3, id: 5, name: 'John'}
 ]

 const obj2 = [
    {key: 2, id: 5, name: 'John'},
    {key: 1, id: 5, name: 'John'},
    {key: 3, id: 5, name: 'John'}
]

function help(obj1, obj2, key) {
  const hashKeyObj2 = obj2.reduce((val, item) => {
    val[item[key]] = item;
    return val;
  }, {});
  return obj1.map((item) => hashKeyObj2[item[key]]);
}

console.log(help(obj1, obj2, 'key'))
0

One-liner

let sorted = obj1.map(a => obj2.find(b => a.key === b.key))
gog
  • 10,367
  • 2
  • 24
  • 38
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Dec 04 '22 at 10:41
0

This snippet will sort obj2 from obj1 order:

const obj1 = [
  { key: 1, id: 5, name: 'John' },
  { key: 3, id: 5, name: 'John' },
  { key: 2, id: 5, name: 'John' },
]

const obj2 = [
  { key: 2, id: 5, name: 'John' },
  { key: 1, id: 5, name: 'Jane' },
  { key: 3, id: 5, name: 'Tom' },
]

function helper(obj1, obj2, key) {
  const findIndex = (refValue) => obj1.findIndex((candidate) => candidate[key] === refValue)
  const comparator = (item1, item2) => findIndex(item1[key]) - findIndex(item2[key])
  return [...obj2].sort(comparator)
}

const result = helper(obj1, obj2, 'key')

console.log('result :', result)
0

An Approach using lodash

function sortArrayBasedOnKeys(
  array1: Record<string, number | string>[],
  array2: Record<string, number | string>[],
  key: string
) {
  const order = _.map(array1, key);
  return _.sortBy(array2, (item) => _.indexOf(order, item[key]));
}

First we are getting order in which objects in the array1 are placed and then using that order to sort the next array.

saumyajain125
  • 93
  • 1
  • 4