Search code examples
javascriptarraysfilter

How to filter array by value between two arrays with more object with javascript?


I have 2 array:

var array1 = 
[{"name":"abc", "url":"http:://example1.com"},
{"name":"cde", "url":"http:://example2.com"},
{"name":"fgh", "url":"http:://example3.com"}];

var array2 = 
[{"id":"1", "url":"http:://example1.com"},
{"id":"2", "url":"http:://example2.com"}]; 

I want to filter array1 with url values that are only in array2 but can't figure out how.

Thank VLAZ about Array Definition. (I thought my example would be a 2-dimensional array).

I known multi-object item array2, I apply the method of reduce array2 to new arrays. But I want to understand more about how to filter directly from 2 arrays with multi object items.

let array2b = array2.reduce((acc, cur) => [...acc, cur.url], []);
var filtered = array1.filter(item => array2b.includes(item.url));

EDIT: I spent a day searching but didn't expect it to be here: Filter array of objects with another array of objects . sorry all


Solution

  • There are a couple of methods in ES6 JavaScript that easily does that: You can use the .filter and .some method.

    In your case, you can format it like the following:

    var array1 = 
    [{"name":"abc", "url":"http:://example1.com"},
    {"name":"cde", "url":"http:://example2.com"},
    {"name":"fgh", "url":"http:://example3.com"}];
    
    var array2 = 
    [{"id":"1", "url":"http:://example1.com"},
    {"id":"2", "url":"http:://example2.com"}]; 
    
    let filteredArray = array1.filter(firstItem => array2.some(secondItem => secondItem.url === firstItem.url)
    

    Explanation: The filter method will allow you to create a new array containing elements that meet a certain condition, and some allows sort of like a checking system to see if at least one element in array2 has the same url as the current element in array1.

    So, in effect, the code allows array1 to be filtered to include only the objects whose url exists in array2.

    You can read more about those two methods for a more generalised understanding but that's how they could be used in your case.

    Hope this helps.