1

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.

6
  • 2
    What have you tried? Also, are they always going to be null for each object in the array so you'd just have to check the first one? Commented Jun 29, 2021 at 0:00
  • @Nick - Updated post Commented Jun 29, 2021 at 0:09
  • Do you guarantee that each object in the array has the same properties? Commented Jun 29, 2021 at 0:14
  • @RobinMackenzie - Yes Commented Jun 29, 2021 at 0:15
  • I don't understand how is "["c", "e"]." the expected result when your question to find null property values in every object of the array [!]? Commented Jun 29, 2021 at 0:42

1 Answer 1

3

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 test every key in the original array for null
  • 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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.