Reputation: 3184
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.
Upvotes: 1
Views: 656
Reputation: 19319
If you guarantee that each object in the array has the same properties then:
reduce
the keys and test every
key in the original array for null
every
key returns true then include the key in the outputExample:
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));
Upvotes: 3