0

I've got two color arrays and I want to return those objects which are in local array and are not available in API response.

API resposne array

[
    {
        "id": 25,
        "color": "#00ad02"
    },
    {
        "id": 28,
        "color": "#e1b12c"
    }

]

Local array

[
    {
        "id": 26,
        "color": "#00ad02",
    },
    {
        "color": "#e1b12c",
        "id": 28,
    }
]

Loop over both arrays and return the one which are not contained by the API response array. Here I am seeking output of id 25.

Chandler Bing
  • 410
  • 5
  • 25
  • @user1672994 i don't think it filters using id, does it? – Chandler Bing Jun 20 '22 at 04:58
  • It is filtering the whole object. If you wanted to work based on id, then you can use map on localResponse to create intermediate array and then use includes to check exist condition. – user1672994 Jun 20 '22 at 05:00
  • 1
    @user1672994 ah includes doesnt work on objects. in that case https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript – cmgchess Jun 20 '22 at 05:00
  • try with `aprResponse.filter(r => !localResponse.some(l => l.id === r.id))` – user1672994 Jun 20 '22 at 05:04
  • works @user1672994 Could you please add it as an answer and a short explanation how this works? – Chandler Bing Jun 20 '22 at 05:07
  • 1
    @random_18 for each element in the apiResponse array it checks if there is an element in localValue array with the same id. thats done with the `some`. but since we need `not` of that it is written as `!localResponse.some....` . some returns true if there is at least one thereforen`!some` returns true if there is none. filter filters out each element that returns true – cmgchess Jun 20 '22 at 05:11
  • @user1672994 thanks very much. Answer question and add this explanation. – Chandler Bing Jun 20 '22 at 05:18
  • Sure, I've added the answer with explanation. – user1672994 Jun 20 '22 at 05:21

2 Answers2

1
apiResponsesArr.filter(resValue => !localArr.some(localValue => localValue.id===resValue.id))
Geeganage
  • 182
  • 1
  • 11
touri
  • 169
  • 1
  • 6
1

The array's filter and some method can be used to find the elements which does not exist in another array.

The filter method creates a new array with all elements that pass the test implemented by the provided function. Read here

The some method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. Read here

const notFoundElements = aprResponse.filter(
  (r) => !localResponse.some((l) => l.id === r.id)
);
Chandler Bing
  • 410
  • 5
  • 25
user1672994
  • 10,509
  • 1
  • 19
  • 32