Ryan Ryan - 18 days ago 7
Javascript Question

Matching two arrays to create a third array

I have an array:

var array = [black, white]


and an object:

var object = [
{color: black, hex: #000000},
{color: white, hex: #ffffff},
{color: red, hex: #ff0000}
]


What I want to do is create a new object from colors that match in both the array and the object, so in this example the new object would be:

var object = [
{color: black, hex: #000000},
{color: white, hex: #ffffff}
]

ray ray
Answer

You could filter the object thusly:

var array = ['black', 'white']

var object = [
    {color: 'black', hex: '#000000'},
    {color: 'white', hex: '#ffffff'},
    {color: 'red', hex: '#ff0000'}
]

var result = object.filter(function(entry) {
  return array.indexOf(entry.color) > -1;
})

console.log(result);