0

Consider below code

I have two arrays with data and need the values that are not present.

var stores = ["1", "2", "3", "4", "5"]; var favStores = ["2", "4"]; outer: for (var i = 0; i < stores.length; i++) { for (var j = 0; j < favStores.length; j++) { if (stores[i] != favStores[j]) { document.write('Stores I : ' + stores[i]); document.write('<br>'); document.write('Fav Stores j : ' + favStores[j]); document.write('<br>'); alert('Match Found' + stores[i]); //continue outer; } } } 

I need my output as

1,3,5 in a new array.

2 Answers 2

4

This way:

var stores = ["1", "2", "3", "4", "5"]; var favStores = ["2", "4"]; var output = stores.filter(function(i){ return favStores.indexOf(i)==-1; }); // output is ["1", "3", "5"] 
Sign up to request clarification or add additional context in comments.

2 Comments

@RaMs_YearnsToLearn: filter function is applied to each element of the array & return value of 'false' will cause it not to be included in the new array.
1

What you need is the difference between the two arrays. Libraries like lodash have that feature but if you want to build your own you can use the following:

var stores = ["1", "2", "3 ", "4", "5"], favStores = ["2", "4"]; function diff(a, b) { var results = []; for(var i = 0; i < a.length; i++) { if(b.indexOf(a[i]) < 0) results.push(a[i]); } return results; } console.log(diff(stores, favStores)); 

Note that you could use forEach to traverse the array but I am just being legacy proof here.

2 Comments

what to do if I have to compare JSON object
That will require more code. You have to iterate on all the supported JSON types (arrays and objects) but also check that values are different and have a strategy for that too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.