Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading