简体   繁体   中英

How to check if there is an item in an array that exists in another array?

I have the following React code that I want to use to disable a button:

todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds) 

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false .

Make checkedIds into a set and then compare them.

var checkedIds = new Set(this.state.checkedIds)
todos.filter( todo => todo.completed === true )
  .map( todo => todo.id )
  .filter( id => checkedIds.has(id) )

You can boil it down even further to the following, assuming todo.completed returns a boolean.

Of course, replace the checkedIds with this.state.checkedIds .

 const todos = [ { id: 1, completed: true }, { id: 2, completed: false }, { id: 3, completed: true }, { id: 4, completed: false } ]; const checkedIds = [1, 2, 4, 5]; const results = todos .filter(todo => todo.completed) .map(todo => checkedIds.includes(todo.id)); console.log(results); 

You can use include in combination with some for succinctness

 var arr1=[1,2,3,4,5,6,7]; var arr2=[8,9,10]; var arr3=[2,1,3,4,5,6,7]; if(arr1.some((x)=> arr2.includes(x))){ console.log('true'); //do something }else{ console.log(false); //do something }; if(arr1.some((x)=> arr3.includes(x))){ console.log('true'); //do something }else{ console.log(false); //do something }; // something even shorter would be arr1.some((x)=> arr2.includes(x))?console.log(true):console.log(false) 

You can just use a simple loop for this:

function arraysIntersect(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        if (arr2.includes(arr1[i])) return true;
    }
    return false;
}

I assume state.checkedIds is an array. If that's true, your code doesn't work because you are checking whether your filtered and mapped todos include checkedIds (which it doesn't) instead of checking whether it includes any of the elements of the array checkedIds (which it might).

You can use my code like this:

var doneTodoIds = todos.filter(todo => todo.completed === true ).map( todo => todo.id).includes(this.state.checkedIds);
var result = arraysIntersect(doneTodoIds, this.state.checkedIds);

You could also solve this with a higher level data structure (Alejandro's suggestion), but that might not be necessary (depending on the context of your code fragment).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM