Access Array within Array

Asked

Viewed 54 times

-3

Good evening, I’m a beginner in Javascript and I’m studying arrays. I have a question, how do I access an item that is in the array within another array?

ex:var numeros = [[01,02,03,04,05],[03,04,05]];

And how I would loop to check if the items of the two arrays are equal?

Thanks in advance.

1 answer

0

Think this outer array has A, B, C. To access these values would be respectively, numeros[0], numeros[1], numeros[2]. Continuing this reasoning, numeros[0][0] would be the 01 which is within the first "sub-"array; and numeros[1][0] would be the 03 in the second "sub-"array.

To know if all the items in the sub-arrays are equal you can do so:

const numeros = [
  ["01", "02", "03", "04", "05"],
  ["03", "04", "05"]
];

const iguais = (a, b, strict) => {

  return a.length === b.length && a.every((el, i) => b.includes(el) && !strict || el === b[i])
}

console.log(iguais([1, 2], [2, 1])); // true
console.log(iguais([1, 2], [2, 1], true)); // false
console.log(iguais([1, 2], [1, 2], true)); // true
console.log(iguais(numeros[0], numeros[1])); // false

To know if one array includes the other you can do so:

const numeros = [
  ["01", "02", "03", "04", "05"],
  ["03", "04", "05"]
];

const includes = (a, b) => {
  return a.every(el => b.includes(el));
}

console.log(includes(numeros[0], numeros[1])); // false
console.log(includes(numeros[1], numeros[0])); // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.