0

For example, if I have 2 arrays being

['dog', 'cat', 'zebra', 'lion', 'cat']

and

['dog', 'cat', 'cat', 'frog']

then a new array should be created that only contains

['dog', 'cat', 'cat']

3 Answers 3

1

You can use two loop for the same and compare them from each other. Ex.

for(let i=0; i<ar1.length; i++)
 {
     for(let j=0; j<ar2.length; j++){
       if(ar1[i]==ar[2])
           res.push(ar[i]);
Sign up to request clarification or add additional context in comments.

Comments

1

const a = ['dog', 'cat', 'zebra', 'lion', 'cat'];
const b = ['dog', 'cat', 'cat', 'frog'];

let result = a.filter(function(obj){
    return b.indexOf(obj) !== -1
})
  
console.log(result)

Comments

1

var array1 = ['dog', 'cat', 'zebra', 'lion', 'cat'];
var array2 = ['dog', 'cat', 'cat', 'frog'];

// Then you can use filter

// const filteredArray = array1.filter(value => array2.includes(value));


// (OR) `indexOf` for old browsers compability

var filteredArray = array1.filter(function(n) {
  return array2.indexOf(n) !== -1;
});

console.log(filteredArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.