Paul Ness Paul Ness - 1 month ago 7
Javascript Question

Create new array based of two different arrays (match values)

I have two arrays in JavaScript and I want to re-arrange one based on the order of the first.

First array:

var arrayOne = [
"5",
"1",
"2",
"4"
]


Second array that I want to re-arrange based on page_id that matches to arrayOne:

var arrayTwo = [
{
"page_id" : "5",
"page_title" : "About"
},
{
"page_id" : "2",
"page_title" : "Home"
},
{
"page_id" : "4",
"page_title" : "Contact Us"
},
{
"page_id" : "1",
"page_title" : "Gallery"
},
];


After re-arranged
I want to re-arrange arrayTwo based on page_id, so once re-arranged the second array will look this like:

var arrayTwo = [
{
"page_id" : "5",
"page_title" : "About"
},
{
"page_id" : "1",
"page_title" : "Gallery"
},
{
"page_id" : "2",
"page_title" : "Home"
},
{
"page_id" : "4",
"page_title" : "Contact Us"
},

];


I'm pretty stuck at this point, I've found many sorting 'solutions' on here and Google but they just don't seem to work. I've tried using a for-loop to do this but I didn't really get anywhere. I wouldn't normally ask for help but I've been stuck for a good 3 hours searching.

The match between the first is matched with
page_id
in the second so there's a match that I can use but as mentioned I'm pretty stuck.

Any help is greatly appreciated, thanks!

Answer

First convert the second array into an object - the key will be the page_id, for example:

var map = arrayTwo.reduce((a, b) => {
  a[b.page_id] = b;
  return a;
}, {});

Now we can easily map the first array, like:

arrayOne.map(x => map[x]);

Working example: http://jsbin.com/tiyudutasi/edit?js,console

Comments