0

I have an array of objects:

let arr = [{id:0, value: 'zero'}, 
           {id:1, value: 'one'}, 
           {id:2, value: ''}]

I need to remove object with empty value. What I am trying:

const removeEmpty = (arr) => {
let filtered = arr.filter(val => val.value != '');
return filtered;

};

Stuck with this:

TypeError: Cannot read property 'filter' of undefined

Edit: corrected syntax

Vladimir B
  • 19
  • 4
  • 2
    How do you invoke `removeEmpty`? – hsz Jul 18 '18 at 11:09
  • Your naming is bad practice - your parameter `arr` shadows the `arr` in the closure. You should rename the parameter, and decide whether you want to use the variable from the closure or the parameter (likely the latter, or you wouldn't need a parameter at all). – ASDFGerte Jul 18 '18 at 11:10
  • 1
    Also, it can be `arr.filter(val => val.value);` – Adelin Jul 18 '18 at 11:10

5 Answers5

2

IMHO, you are looking for something like this:

var arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];

var filteredArr = arr.filter(obj => obj.value != '')
console.log(filteredArr);
           
 

NOTE: Your's is not a proper array (because Objects inside it are invalid).

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
0

You missed a comma on the value of id and a quote for the value of the value property

let arr = [{id:0, value: "zero"}, 
           {id:1, value: "one"}, 
           {id:2, value: ''}];
           
           
console.log(arr.filter(a => a.value != ''));
Joven28
  • 769
  • 3
  • 12
0

Seems your arr is not correct i.e object key value pair is not valid

let arr = [{id:0, value: 'zero'}, {id:1, value: 'one'},  {id:2, value: ''}];

const removeEmpty = (arr) => {
  let filtered = arr.filter(val => val.value !== ''); 
  return filtered;
}

removeEmpty(arr)
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

This questions is already answered in below link, Please have a look

Click here!

Ninja
  • 338
  • 4
  • 12
0

Following code will be helpful in more cases, for instance if object value is: false, null, empty string or undefined.

let arr = [
  {id:0, value: 'zero'}, 
  {id:1, value: 'one'}, 
  {id:2, value: ''},
  {id:3, value: false},
  {id:4, value: null},
  {id:5}
];

const filteredArr = arr.filter(obj => obj.value);  

console.log(filteredArr);
syntax-punk
  • 3,736
  • 3
  • 25
  • 33