Home > Blockchain >  Sort an array based on another array that stores the position
Sort an array based on another array that stores the position

Time:12-21

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}]

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}]

CodePudding user response:

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);

CodePudding user response:

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

let arr2 = [{
  groupName: "test2",
  otherValue: 10
}, {
  groupName: "test",
  otherValue: 20
}];

let output = [];

arr1.map((e, i, arr) => {
  let value = arr2.find(j => j.groupName === e.groupName);
  output.push(value);
})
console.log(output);

  • Related