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
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
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, returningtrue
orfalse
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);
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)))
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