Home > Back-end >  Sort array of arrays by another array's elements JS
Sort array of arrays by another array's elements JS

Time:09-20

Many similar questions but none seem to really apply to this.

I am trying to sort the order of arrays in ArrayA based on the elements in ArrayB in JavaScript

For example, ArrayA and ArrayB are as follows.

ArrayA = [
    ['1', '123', '321'],
    ['2', '456', '654'],
    ['3', '789', '987'],
    ['4', '420', '314']
]

ArrayB = ['2', '1', '4', '3'];

I basically want to map the order of the arrays inside ArrayA to match the order of the elements in ArrayB. I want to be able to do this with any sized arrays not just 4... (assuming they are the same size)

The desired output is below:

ArrayA = [
    ['2', '456', '654'],
    ['1', '123', '321'],
    ['4', '420', '314'],
    ['3', '789', '987']
]

I've tried many .sort() solutions and manual loops and nothing seems to work (such as the one below and yes I know its wrong). So just wondering if anyone has any ideas. TIA!

ArrayA.sort((a, b) => ArrayB.indexOf(a.ArrayA) - ArrayB.indexOf(b.ArrayA));

CodePudding user response:

You can use Array#sort with Array#indexOf as follows:

const
    ArrayA = [
        ['1', '123', '321'],
        ['2', '456', '654'],
        ['3', '789', '987'],
        ['4', '420', '314']
    ],

    ArrayB = ['2', '1', '4', '3'],
    
    Ordered = ArrayA.sort(
        //since each element of ArrayA is an array with 3 elements
        //[a] or [a,,] denotes the first element as a
        //[b] or [b,,] is also the first element of the element of
        //ArrayA being compared, else you have to use:
        //(a,b) => ArrayB.indexOf(a[0]) - ArrayB.indexOf(b[0])
        ([a],[b]) => ArrayB.indexOf(a) - ArrayB.indexOf(b)
    );
    
    console.log( Ordered );

REF

Destructuring

CodePudding user response:

using normal for loop

const ArrayA = [
  ["1", "123", "321"],
  ["2", "456", "654"],
  ["3", "789", "987"],
  ["4", "420", "314"],
];

const ArrayB = ["2", "1", "4", "3"];

const sorted = (a, b) => {
  let result = [];

  for (let i = 0; i < a.length; i  ) {
    for (let j = 0; j < b.length; j  ) {
      if (a[i][0] === b[j]) {
        result.push(a[j]);
        break;
      }
    }
  }

  return result;
};

console.log(sorted(ArrayA, ArrayB));

basically, we check if the number in arrayA is equal to the number in B,
if yes we push the current array, and we break the loop and continue repeating until we finish

this solution is great if you want:

  • without any other external methods
  • native code
  • Related