-4

This was bothering me for hours...and I don't understand yet why. I have an array of of objects. Is my syntax bad for the ternary?...

This is in React if that matters.
The array is something like below

[{id:1, name:'steve'}, {id:2, name:'john'}] 

if i use this, it works fine.

array.filter(item => { if (item.id ==id) return item.name} )

if I use this, it returns me the whole array, without filtering nothing.

array.filter(item => item.id ===id ? item.name : 'null')

.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
born2gamble
  • 197
  • 7
  • 17

3 Answers3

4

Why not just take the result of the comparison, as Array#filter expects a boolean value?

array.filter(item => item.id === id)

The return value of the callback does not change anything outside of filter, just the result of the filtering.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

Array.filter() works by selecting those elements from the array for which true value is returned. Which does not mean the boolean true value but any values that is defined. So, in your code you are returning null with quotes for the else part which is a string and not actually a null value. Thus, it considers it as a truthy and consider that object in the filtered array. Change that to null and it will work.

var array = [{
    id: 10,
    name: "name10"
  },
  {
    id: 20,
    name: "name20"
  }
];
var id = 20;
var res = array.filter(item => item.id === id ? item.name : null);
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You are using filter wrong.
You can check the documentation and see that callback parameter is a function that returns true or false.
So in your case - you want to filter array by id and then select only name.
You can chain filter and map.

For example,

let array = [{id:1, name:'steve'}, {id:2, name:'john'}];
let result = array
  .filter(item => item.id === 1)
  .map(item => item.name);

console.log(result);
qwermike
  • 1,446
  • 2
  • 12
  • 24