Luiz
Luiz

Reputation: 459

Return true or false using map arrays

I need to return a boolean value to assign to my form's checkboxes by checking if the value exists in the array.

For this I've been trying to use .map() by traversing a list of ID's and checking if this id exists within that list by returning an array of Boolean values.

const arrayOne = ['id1', 'id2', 'id3', 'id4', 'id5'];
const arrayTwo = ['id4'];
const booleanValues = [false, false, false, true, false]; // expected outcome

How to check if the id exists in another array returning boolean values using .map() in a simplified and readable way?

Upvotes: 0

Views: 8014

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45745

I'd just use includes to see if the value of arr is present in checkVals:

var arr = [1, 2, 3];
var checkVals = [2];
    
var results = arr.map(n => checkVals.includes(n));
    
console.log(results);
// [false, true, false]

Instead of using an array for checkVals, you could also use a Set for better performance. That's likely not necessary here though.

Upvotes: 4

Related Questions