0

will be very simple question,

I have these two arrays:

var pcNumbers = [1,2,3,4,5];
var userNumbers = [1,2,7,8,9];

Pratically i have to find a way to create an alert who say "There are two elements in common, 1 and 2"

Tyia

4

3 Answers 3

7

You can filter one array by checking each item in another using Array.prototype.filter()

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

and Array.prototype.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

var pcNumbers = [1,2,3,4,5];
var userNumbers = [1,2,7,8,9];
var commonNumbers = pcNumbers.filter(i => userNumbers.includes(i));
console.log(commonNumbers);

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

2 Comments

btw, don't use var, use let instead.
@ʎzɐɹƆ do not use let if you are not re-assigning. Use const.
3

Well, this is really simple question.

Go through the 1st array and check if each element appears in the 2nd array.

If so, push it to another array or just display it.

const a = [1,2,3,4,5,6,7,8,9,10];
const b = [2,4,5,7,11,15];

for(let i of a){
  if(b.includes(i)){
    console.log(i)
  }
}
--------- OR --------------
console.log(a.filter(e => b.includes(e)))

Comments

1

A quick solution could be something like this:

const pcNumbers = [1,2,3,8,5];
const userNumbers = [1,2,7,8,9];
const newArr = [];

for (let i = 0; i < pcNumbers.length; i++) {
    for (let j = 0; j < userNumbers.length; j++) {
        if (pcNumbers[i] === userNumbers[j]) {
            newArr.push(pcNumbers[i])
        }
    }
};

console.log(`These are in common: ${newArr.join(', ')}`)

This will result in:

These are in common: 1, 2

3 Comments

what's the expected result for [1,2,3,8,5] and [1,2,7,8,9,2] @Emanuel Rista
This would be an edge case. You can always check if the number is in the array before you push it. For example: if (!(pcNumbers[i] in newArr)) { newArr.push(pcNumbers[i]) } - In this case, you will do a lot of looping, and a better solution would be to add the numbers to a JS object instead (hash table). That would make the lookup a faster, but would require a bit different code.
So I am just saying that this is the best efficient solution. :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.