Reputation: 25
I have 2 arrays, one has 10 elements and the other one 3, I need to create a new array with the same size of the biggest vector, with a boolean checking true in the position where exist some element from the array of 3 elements
I have the following arrays
array1 = [1,2,3,4,5,6,7,8,9,10]
array2 = [4,6,10]
I tried making 2 for loops
for(var i=0; i<array1.lenght; i++){
for(var j=0; i<array2.lenght; i++){
if(array1[i]==array2[j]){
array3.push(true)
}else{
array3.push(false)
}
}
}
the vector that I need would be
array3 = [false, false, false, true, false, true, false, false, false, true]
Upvotes: 0
Views: 1022
Reputation: 57
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const finalArray = [];
for (let data of array1) {
finalArray.push(array2.includes(data));
}
Upvotes: 0
Reputation: 1616
I would suggest to keep things simple and to use Array#indexOf method to determine if array contains another element.
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const b = array1.map(el => {
return array2.indexOf(el) !== -1;
});
console.log(b);
Upvotes: 0
Reputation: 18525
You can also instead of another array use a Set and then Array.map the first away checking if the value is in the Set:
let array1 = [1,2,3,4,5,6,7,8,9,10],
set = new Set([4,6,10])
let result = array1.map(x => set.has(x))
console.log(result)
Upvotes: 1
Reputation: 44125
Use map
like so with shift
like so:
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const array3 = array1.map(e => {
if (array2[0] == e) {
array2.shift();
return true;
}
return false;
});
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: auto; }
If you just want a basic check as for whether the element is in the array, not the order, then use includes
.
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [4, 6, 10];
const array3 = array1.map(e => array2.includes(e));
console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Upvotes: 2
Reputation: 18975
You can forEach
first array and use include
method to check if item existed in array as
let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let array2 = [4, 6, 10];
let array3 = [];
array1.forEach(function (c) {
if (array2.includes(c)) {
array3.push(true)
} else {
array3.push(false);
}
})
console.log(array3)
Upvotes: 2