Home > Enterprise >  Best way to loop through an array and return the sub arrays that match the first 2 values
Best way to loop through an array and return the sub arrays that match the first 2 values

Time:12-08

Let's say I have 4 arrays:

var arrays =  [
    [1, 2, 1],
    [1, 3, 4],
    [1, 2, 3],
    [0, 2, 2]
];

And I want to return the child/sub arrays that start with both 1 and 2, what type of loop would I need?

Currently, this is what I have:

var arrays =  [
    [1, 2, 1],
    [1, 3, 4],
    [1, 2, 3],
    [0, 2, 2]
];
        
var selected = [1, 2]; // These are the values that need to match
var result = [];
for (var i = 0; i < selected.length; i  ) {
    for (var j = 0; j < arrays.length; j  ) {
        if (arrays[i][j] === selected[i]) {
            result.push(arrays[i]);
        }
    }
}

When there's more than 1 value in the selected array, it seems to return all the ones that match 2 on the second index, so the result would be:

[
    [1, 2, 1],
    [1, 2, 3],
    [0, 2, 2]
]

The loop needs to ensure that on the second iteration it's making sure the first value is still true, as my intended result would be:

[
    [1, 2, 1],
    [1, 2, 3]
]

Please someone help me, I've had my head trying hundreds of different loop and checks variations for 2-3 days.

Thanks so much!!

Jake

CodePudding user response:

Your current code pushes to the result array whenever any given index matches between arrays and selected. Instead you will need to reverse your loops and iterate over selected for every sub array and check if every element matches, if not break the inner loop and don't push.

const arrays = [
  [1, 2, 1],
  [1, 3, 4],
  [1, 2, 3],
  [0, 2, 2],
];

const selected = [1, 2]; // These are the values that need to match
const result = [];

for (let i = 0; i < arrays.length; i  ) {
  let match = true;
  for (let j = 0; j < selected.length; j  ) {
    if (arrays[i][j] !== selected[j]) {
      match = false;
      break;
    }
  }
  if (match) {
    result.push(arrays[i]);
  }
}

console.log(result);

A more modern solution would be to use filter() with a nested every() call on selected.

const arrays = [
  [1, 2, 1],
  [1, 3, 4],
  [1, 2, 3],
  [0, 2, 2],
];

var selected = [1, 2];
const result = arrays.filter(arr => selected.every((n, i) => n === arr[i]));

console.log(result);

CodePudding user response:

Here is another approach where you turn both arrays to string and check it those inner arrays start with selected array.

var arrays = [
  [1, 2, 1],
  [1, 3, 4],
  [1, 2, 3],
  [0, 2, 2]
];

var selected = [1, 2];
const result = arrays.filter(e => e.toString().startsWith(selected.toString()))
console.log(result)

  • Related