Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort an array based on another array that stores the position

I want to sort an based on another array that stores the position. They have in common groupName. For example:

array1 = [ {groupName: "test", position: 0}, {groupName: "test2", position: 1}]

array2 = [ {groupName: "test2, otherValue: 10}, {groupName: "test", otherValue: 20}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At the end I want to get the data from the second array but with the right positions:
array = [{groupName: "test", otherValue: 20}, {groupName: "test2", otherValue: 10}]

>Solution :

You need to use .sort but for each item you compare you need to get the position from the other array.

So

const array1 = [{
  groupName: "test",
  position: 0
}, {
  groupName: "test2",
  position: 1
}]

const array2 = [{
  groupName: "test2",
  otherValue: 10
}, {
  groupName: "test",
  otherValue: 20
}]

const array = array2.slice().sort((a, b) => {
  const posA = array1.find(({
    groupName
  }) => groupName === a.groupName).position;

  const posB = array1.find(({
    groupName
  }) => groupName === b.groupName).position;
  
  return posA-posB;
});

console.log(array);

Now if that was a huge array, you might want to cache the position to avoid searching for each compare

const array1 = [{
  groupName: "test",
  position: 0
}, {
  groupName: "test2",
  position: 1
}]

const array2 = [{
  groupName: "test2",
  otherValue: 10
}, {
  groupName: "test",
  otherValue: 20
}]

const positions = array1.reduce((acc, item) => ({
  ...acc,
  [item.groupName]: item.position
}), {});


const array = array2.slice().sort((a, b) => {
  return positions[a.groupName] - positions[b.groupName];
});

console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading