Vikas Acharya
Vikas Acharya

Reputation: 4162

how to get only boolean value from a nested array

This might seems silly, but I'm trying it from long time.

var parentArray = [
  [0.49988811188811194, 0.17249417249417248],
  [0.8181398601398602, null],
  [0.8181398601398602, 0.47785547785547783],
  [0.49988811188811194, 0.47785547785547783]
];

function containsNull(arr) {
  return (function() {
    return arr.filter(e => {
      if(e.some(el => el == null)) return true
    })
  })();
}

console.log("-->", containsNull(parentArray))

here I'm getting output as

> "-->" Array [Array [0.8181398601398602, null]]

but I don't need the array as return value. I just want true or false that's all.

i.e, 

"-->" true

How to achieve this? even using load-ash library is good to go!

Upvotes: 1

Views: 674

Answers (3)

Rahul Kumar
Rahul Kumar

Reputation: 3157

Use Array.some() method on both parent and child array.

var parentArray = [
  [0.49988811188811194, 0.17249417249417248],
  [0.8181398601398602, null],
  [0.8181398601398602, 0.47785547785547783],
  [0.49988811188811194, 0.47785547785547783]
];

function containsNull(arr) {
  return arr.some(list => list.some(ele => !ele))
}

console.log(containsNull(parentArray));

Upvotes: 0

Capt 171
Capt 171

Reputation: 665

It seems that you are using a multidimensional array, so you could just flatten it with Array.prototype.flat and use Array.prototype.includes to check if the flattened array contains null.

let parentArray = [
  [0.49988811188811194, 0.17249417249417248],
  [0.8181398601398602, null],
  [0.8181398601398602, 0.47785547785547783],
  [0.49988811188811194, 0.47785547785547783]
];

const containsNull = (arr) => arr.flat().includes(null)

console.log(containsNull(parentArray))

The following would flatten arrays of n-dimensions and check if it contains null:

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

let parentArray = [
  [[[[0.49988811188811194, 0.17249417249417248]]],
  [0.8181398601398602, null],
  [0.8181398601398602, 0.47785547785547783]],
  [0.49988811188811194, 0.47785547785547783]
];

const containsNull = (arr) => flatten(arr).includes(null)

console.log(containsNull(parentArray))

Upvotes: 2

DecPK
DecPK

Reputation: 25401

You can use some with includes

var parentArray = [
  [0.49988811188811194, 0.17249417249417248],
  [0.8181398601398602, null],
  [0.8181398601398602, 0.47785547785547783],
  [0.49988811188811194, 0.47785547785547783],
];

const result = parentArray.some((a) => a.includes(null));
console.log(result);

Upvotes: 2

Related Questions