For example, if I have a JavaScript array of objects such as:
var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, b: 8, c: null, d: 1, e: null} ];
I would expect the output to be [“c”, “e”].
My current solution is to call a function for each column & loop through the jsObjects:
function isAllNull(col) { var allNulls = true; for (var i = 0; i < data.length; i++) { if (jsObjects[i].col != null) { allNulls = false; break; } } }
But I would like for this function to be more generic such that it will jsObjects with any number of arbitrary simple (i.e. not objects) properties. The objects in the array all have the same properties.
Advertisement
Answer
If you guarantee that each object in the array has the same properties then:
- take the keys from the first object in the array
reduce
the keys and testevery
key in the original array fornull
- if
every
key returns true then include the key in the output
Example:
var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, b: 8, c: null, d: 1, e: null} ]; function nullCols(arr) { var keys = Object.keys(arr[0]); var nulls = keys.reduce((output, key) => { if (arr.every(item => item[key] === null)) { output.push(key); } return output; }, []); return nulls; } console.log(nullCols(jsObjects));