2

I have this array and I want to to get a boolean(true) if there is a 'three' that is equal to 9

myArr = [ { apple: 6, basket: [ { one: 1, two: 2, three: 3 }, { one: 4, two: 5, three: 6 } ] }, { apple: 9, basket: [ { one: 1, two: 2, three: 3 }, { one: 4, two: 5, three: 9 } ] } ]

What I tried:

enter code here

this.myArr.forEach( data => {
      if(data.basket.filter(cur => cur.one === 0 || cur.three === 9)) {
       console.log('true')
      }
    })

This always logs true for some reason I don't know why.

2 Answers 2

4

.filter will always return an array of elements which pass the test, and arrays are truthy. Even if no elements pass the test, the array will still be truthy:

const arr = [1, 2, 3].filter(() => false);
if (arr) {
  console.log('truthy');
}

Use .some instead, to see if there is at least one element which passes the test:

const myArr = [{
  apple: 6,
  basket: [{
    one: 1,
    two: 2,
    three: 3
  }, {
    one: 4,
    two: 5,
    three: 6
  }]
}, {
  apple: 9,
  basket: [{
    one: 1,
    two: 2,
    three: 3
  }, {
    one: 4,
    two: 5,
    three: 9
  }]
}]

myArr.forEach(data => {
  if (data.basket.some(cur => cur.one === 0 || cur.three === 9)) {
    console.log('true');
  }
});

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

2 Comments

Wouldn't some() stop looping if it finds a value that match the condition? Thank you very much
Yes, but that's what you want, right? As you said: I want to to get a boolean(true) if there is a 'three' that is equal to 9
0

filter returns to array and use find which will return matched item or null when no match.

In you code, Just change from filter to find will work fine.

const myArr = [
  {
    apple: 6,
    basket: [
      { one: 1, two: 2, three: 3 },
      { one: 4, two: 5, three: 6 }
    ]
  },
  {
    apple: 9,
    basket: [
      { one: 1, two: 2, three: 3 },
      { one: 4, two: 5, three: 9 }
    ]
  }
];

const items = myArr.map(data =>
  data.basket.find(cur => cur.one === 0 || cur.three === 9) ? "true" : "false"
);

console.log(items);

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.