Ryan Ryan - 1 year ago 91
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 Source

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;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download