I want to filter out items that are not pairs from this array let (pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"];)

Viewed 29

This is the array I am working with I want to remove the null, false and "whoops" using the filter method

let pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"];
1 Answers

You can check it by using Array.isArray() method.

const filtered = pairsByIndexRaw.filter(pre => Array.isArray(pre))

Array.prototype.filter will loop over each element in your array, if it returns true In case if element is array then the element is added to the filtered array otherwise it is skipped.

If you only need pairs then

const filtered = parisByIndexRaw.filter(pre => Array.isArray(pre) && pre.length === 2)

The snippet above will check if the item is an array and has exact length of two.

Related