1

I want to filter array of objects in javascript. I am using filter function for it.

let data=[
    {
        "label": "12:00 am",
        "value": 0
    },
    {
        "label": "12:30 am",
        "value": 30
    },
    {
        "label": "1:00 am",
        "value": 60
    },
];
val=20;
new_data=data.filter(item=>{
    return item.value>val
})
console.log(new_data)//  [ { label: '12:30 am', value: 30 }, { label: '1:00 am', value: 60 } ] //expected results`

If am filtering it like

new_data=data.filter(item=>{
    item.value>val;
})

without using return keyword I am getting empty array. Why do we need to use return keyword in the above example code to work? Why in case of arrays of strings we do not need return statement in the below example?

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) =>  reword.length > 6);
  • 2
    it is the `{}`. with that u need return. try with `new_data=data.filter(item=>item.value>val)` – cmgchess Aug 20 '23 at 15:37
  • It is to do with ES6 syntax that allows the function to automatically return an array, but it depends on the syntax. Generally if you are calling the parentheses you would be doing more inside the function, the example you added uses an explicit return. See https://dev.to/samanthaming/es6-arrow-functions-cheatsheet-1cn – lharby Aug 20 '23 at 15:49
  • because `item => { item.value>val;}` doesn't return an object, but is a function which doesn't return anything (ie a falsey, that that's because the respective element isn't kept by `filter`) If you just want the boolean check, so it the same as you do with the string: `item => item.value > val` – derpirscher Aug 20 '23 at 15:50

1 Answers1

2

If an arrow function only has one statement, then you can omit the {} and it's implicitely returned, e.g. in the case of:

() => 6

it automatically becomes

() => {
  return 6;
}

Otherwise, when using the long form with the {}, you have to return yourself. This is useful if you want to write a longer function, and allows you to do e.g. early returns, etc:

(item) => {
  const x = someFunc(item);
  if (x < 0) return 0;

  const y = otherFunc(item);

  return x + y;
}
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55