Search code examples
javascriptarraysjavascript-objects

javascript count objects in array of objects without null values


Let's say we have array of objects:

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

and want to get length of the array but exclude counting of the objects which has null values (in example above, this is the last object with address property null) so that result of the counting of the example above would be 2.

objectsWithoutNull = data.reduce(function (r, a) {
    return r + +( a!== null);
}, 0);

I'm trying with reduce method, but got 0. Where is the problem in iteration?


Solution

  • Reduce the array, for each object get the values with Object.values(), and check with Array.includes() if it contains a null value. Negate with ! the boolean result of inclues, and use the + operator to convert to number. Add the number to the accumulator.

    const data = [{"firstName":"Bruce","lastName":"Wayne","address":"Arkham 6","id":"1"},{"firstName":"Peter","lastName":"Parker","address":"LA 54","id":"2"},{"firstName":"Tony","lastName":"Stark","address":null,"id":"3"}];
    
    const result = data.reduce((r, o) => 
      r + +!Object.values(o).includes(null)
    , 0);
    
    console.log(result);