0
econst ELEMENT_DATA: PeriodicElement[] = [
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}
];

How return boolean if the value is inside of this array?
some thing like this

ELEMENT_DATA.includes({name: 'Helium'});
>True
str
  • 42,689
  • 17
  • 109
  • 127
Dan Jhay
  • 150
  • 4
  • 9

2 Answers2

7

Use Array.some method which will tests whether at least one element in the array passes the test

const ELEMENT_DATA = [{
    position: 1,
    name: 'Hydrogen',
    weight: 1.0079,
    symbol: 'H'
  },
  {
    position: 2,
    name: 'Helium',
    weight: 4.0026,
    symbol: 'He'
  },
  {
    position: 3,
    name: 'Lithium',
    weight: 6.941,
    symbol: 'Li'
  },
  {
    position: 4,
    name: 'Beryllium',
    weight: 9.0122,
    symbol: 'Be'
  }
];
let m = ELEMENT_DATA.some(function(item) {
  return item.name === 'Helium'
});
console.log(m)
brk
  • 48,835
  • 10
  • 56
  • 78
1

You could handover array, key and value for checking the objects.

function check(array, key, value) {
    return array.some(object => object[key] === value);
}

var periodicElements = [{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' }, { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }, { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' }, { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' }];

console.log(check(periodicElements, 'name', 'Helium'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392