NinjaDeveloper
NinjaDeveloper

Reputation: 1712

filter return true or false

I'm using filter to find id in data.it return object not true or false.

How can I return true or false if val.recoredId === valueId ?

var hasMatch = data.filter(function (val) {
  return (val.recordId === valueId);
});
        

Upvotes: 7

Views: 51461

Answers (4)

gurvinder372
gurvinder372

Reputation: 68393

Just check the length of filtered results.

var hasMatch = data.filter(function (val) {
  return (val.recordId === valueId);
}).length > 0;

Upvotes: 27

JeffBeltran
JeffBeltran

Reputation: 739

While calling filter with length appended does resolve this, I would point you to the some() method

hasMatch = data.some(function (value) {
   return value.recordId == valueId
});

This will return a boolean if the array contains any matching value.recordId == valueId entries

Upvotes: 15

user5211381
user5211381

Reputation:

use find

 hasMatch = data.find(function (value) {return value.recordId == valueId });

Upvotes: 8

Sapotero
Sapotero

Reputation: 179

try this

var hasMatch = data.filter(function (val) {
    return !!(val.recordId === valueId);                               
});

Upvotes: 1

Related Questions