2

I'm trying to make a third array out of two arrays. I want to check if array 2 contains array 1 elements.

So Array2 could look like:

["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX" ]

Array 1:

["Bol", "Amazon","XBOX"]

Array 3 should then be:

["Bol", "Amazon", "XBOX"]

But most of the outcomes are only XBOX (so, array1.val full match array2.val).

I've tried the following:

var array1 = ["Bol", "Amazon", "XBOX"],
  array2 = ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX"],
  array3 = [];


array3 = array1.filter(function(store) {
  return array2.includes(store);
});
console.log(array3);

array3 = array1.filter(function(store) {
  return array2.indexOf(store) >= 0;
});
console.log(array3);

var storesToCheck = function(array1, array2) {
  return array1.some(function(value) {
    return array2.indexOf(value) >= 0;
  });
};

console.log(storesToCheck(array1, array2));

1
  • Please note the snippet I made for you. It is called a minimal reproducible example - please provide such a thing in the future after some research. Commented Jun 6, 2018 at 12:05

1 Answer 1

3

You can use includes method in combination with some by passing a callback provided function as argument.

arr2 = ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX" ]
arr1 =  ["Bol", "Amazon","XBOX"]

console.log(arr1.filter(a => arr2.some(item => item.includes(a))));

Sign up to request clarification or add additional context in comments.

1 Comment

If arr2 = ["Bol Sales ", "BookStore Amazon Sales", "Nintendo Sales", "XBOX" ] and arr1 = ["Bol", "Amazon","XBOX","Sales"] Your code Output is ["Bol", "Amazon","XBOX","Sales"]... So kindly check your logic...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.