admin管理员组

文章数量:1406444

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 oute

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

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 oute

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

Share edited Jan 31, 2019 at 1:51 buydadip 9,45722 gold badges93 silver badges160 bronze badges asked Sep 24, 2018 at 0:20 LuizLuiz 4591 gold badge9 silver badges17 bronze badges 1
  • I have already tried some forms, but none that was legible of easy understanding ... I know how easy it is but I am not able to create something simple with readability. – Luiz Commented Sep 24, 2018 at 0:24
Add a ment  | 

1 Answer 1

Reset to default 4

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.

本文标签: javascriptReturn true or false using map arraysStack Overflow