js-learner
js-learner

Reputation: 507

How do I match ordering of 2 different arrays, that have the same items?

I have 2 javascript arrays:

const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];
const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];

PS- I cant change/control order of 'arr1'

My question is how can I make the order of the items of 'arr2' match that of 'arr1'.

I have been thinking it might look something like:

//1. Some kind of function to get index of all items
const items = (item) => item === item; 
const arr3 = arr1.findIndex(items);

//2. Then think I need to get the values of arr2 using ([Array.values()][1])**
const arr2vals = arr2.values();

//3. Then some kind of calculation that matches the values, this is where I really struggle more, but weak at best lol!
arr3.filter(value => arr2vals.includes(value))

** Ref: MDN

Upvotes: 0

Views: 1918

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an object which keeps the order values of the items and sort the second array with the delta of the values.

Please have a look to Array#sort and the sorting with numbers.

Maybe you ask, why not using zero as value? This approach allows to use a default value by using this pattern:

array2.sort((a, b) => (order[a] || defValue) - (order[b] || defValue));

defValue can be

  • -Number.MAX_VALUE a negative large number which sorts all items without an order to top of the array,
  • Number.MAX_VALUE a positive large number which sorts all items without an order to bottom of the array,
  • or any other number for getting a sorting inbetween the wanted order.

const
    array1 = ['one', 'two', 'three', 'four', 'five', 'six'],
    array2 = ['five', 'six', 'four', 'three', 'one', 'two'],
    order = Object.fromEntries(array1.map((value, index) => [value, index + 1]));

array2.sort((a, b) => order[a] - order[b]);

console.log(...array2);

Upvotes: 1

Moshe Sommers
Moshe Sommers

Reputation: 1516

You can use array.sort

const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];
const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];

/**
Takes in a compare function as parameter where ordering is decided 
based on a more less or equal to 0 return value. 
More than 0 says next should have a lower index than prev
Less Than 0 puts next at a higher index and 0 keeps them at the same index
*/
arr2.sort((prev, next) => {
    return  arr1.indexOf(prev) - arr1.indexOf(next);
})

MDN docs

Upvotes: 2

Related Questions