Home Ask Login Register

Developers Planet

Your answer is one click away!

sobo sanrex February 2016

Compare values in two arrays using Iterator in Javascript?

I know how to compare values in two arrays using 2 for loops however I was looking for something a bit more sophisticated like creating an iterator to iterate through one of the arrays and passing the other array to mapmethod . Is that even possible?

I'm doing a small program for class which takes an array and x arguments and I currently have extracted the values from the arguments.

function dest(arr){
  var args =[];
  for(var i = 1; i < arguments.length; i++){

  return args;

console.log(dest([1, 2, 3, 4], 4, 4));

Now, how could I do the iterator part to compare the values inside arr and args? Thanks for the help.

The result should be the results that match from both arr and args.


Jarno Lonardi February 2016

You can use the built in filter method

var arr = [2, 3, 4, 5, 6];
var args = [3, 5, 6, 7];

var result = arr.filter(function(element) {
    return args.indexOf(element) > -1;

This will filter out all the elements out that are not present in both arrays. The result is a new array that contains only the matching values [3, 5, 6].

Post Status

Asked in February 2016
Viewed 2,921 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life