gpbaculio
gpbaculio

Reputation: 5968

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.

Upvotes: 0

Views: 101

Answers (4)

Rick
Rick

Reputation: 1055

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)

Upvotes: 1

timolawl
timolawl

Reputation: 5564

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);

Upvotes: 1

11684
11684

Reputation: 7507

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).

Upvotes: 0

Alejandro C.
Alejandro C.

Reputation: 3801

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) )

Upvotes: 1

Related Questions