How to create filtered json array with non-zero, numeric elements from JSON array in JavaScript

1 Answer

0 votes
var arr = [
  { id: 17 },
  { id: -4 },
  { id: 129 },
  { id: 0 },
  { id: 3.14 },
  { },
  { id: NaN },
  { id: null },
  { id: 'undefined' }
];

function filterByIDandNumbers(obj) {
  if ('id' in obj && typeof(obj.id) === 'number' && !isNaN(obj.id)) 
    return true;
  else 
    return false;
}

var arr = arr.filter(filterByIDandNumbers);

console.log('Filtered Array', arr); 
  
  
/*
run:  
 
Filtered Array [Object { id=17}, Object { id=-4}, Object { id=129}, 
                Object { id=0}, Object { id=3.14}]
  
*/

 



answered May 21, 2016 by avibootz
...