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
3
  • some thing like this ELEMENT_DATA.includes({name: 'Helium'}); >True Commented Aug 30, 2018 at 18:57
  • I see a single-dimensional array in your code. An array of objects specifically. Commented Aug 30, 2018 at 18:58
  • 1
    Possible duplicate of Find object by id in an array of JavaScript objects Commented Aug 30, 2018 at 18:59

2 Answers 2

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)

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.