-1

Here my array :

[{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}]

I try to return true or false if an id is present in this array :

array.includes(2) -> true
array.includes(7) -> false

I need to do this on the id index of each object of the array.

I know i can use a foreach on each id of the array, but i want to use a cleanest way to do this. What can i use ? Thanks !

4

2 Answers 2

3

Operating Array.prototype.some directly at the given array, one can write ...

array.some(({ id }) => id === yourID)

... or one uses a more generic approach like ...

var array = [
  { id: 1, value: 'blabla' },
  { id: 2, value: 'blabla' },
  { id: 3, value: 'blabla' },
];

function hasItemWithKeyAndValue(arr, key, value) {
  return arr.some(item => item[key] === value);
}

// what the OP did ask for.
console.log(
  "hasItemWithKeyAndValue(array, 'id', 1) ?",   // true
  hasItemWithKeyAndValue(array, 'id', 1)
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', '1') ?", // false
  hasItemWithKeyAndValue(array, 'id', '1')
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', 3) ?",   // true
  hasItemWithKeyAndValue(array, 'id', 3)
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', 4) ?",   // false
  hasItemWithKeyAndValue(array, 'id', 4)
);

// proof of the generic key value approach.
console.log(
  "hasItemWithKeyAndValue(array, 'value', 'blabla') ?", // true
   hasItemWithKeyAndValue(array, 'value', 'blabla')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

Try this array.some(item => item.id === yourID) @Tony S
The most compact way is array.some(({id}) => id === yourId).
0

You can use Array.some():

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];
arr.some(e => e.id === 1);
// -> true

If you want an approach like Array.includes() you can extend the Array prototype:

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];

Array.prototype.hasId = function(id){
    return this.some(e => e.id === id);
};

console.log(arr.hasId(1));
console.log(arr.hasId(3));
console.log(arr.hasId(4));


Otherwise I'd just wrap it inside a function:

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];


let hasId = function(arr, id){
    return arr.some(e => e.id === id);
};

console.log(hasId(arr, 1));
console.log(hasId(arr, 2));
console.log(hasId(arr, 4));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.