Welcome to a quick tutorial on the nested array in Javascript. So you have finally met the worthy opponent called the multidimensional array, and this “array in an array” thing sure is confusing. How do we create one? Add elements to it? Find an element inside? Let us walk through some examples – Read on!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
NESTED ARRAY EXAMPLES
All right, let us now get into the various examples on how to work with a nested array in Javascript.
1) HOW TO DEFINE A NESTED ARRAY
// (A) NESTED ARRAY
var arr = [
"Foo Bar", // first - string
123, // second - number
true, // third - boolean
["Hello", "World"], // forth - array
{ name:"Jon", gender:"M" }, // fifth - object
text => alert(text) // sixth - function
];
// (B) THE ELEMENTS
console.log(arr[0]); // Foo Bar
console.log(arr[1]); // 123
console.log(arr[2]); // true
console.log(arr[3]); // ["Hello", "World"]
console.log(arr[4]); // { name : "Jon", gender : "M" }
console.log(arr[5]); // text => alert(text)
When it comes to creating a nested array, some beginners immediately foam in the mouth and go on a “very difficult trance”. No idea why.
- We can literally put almost anything in an array – Strings, numbers, boolean, objects, functions, and other arrays.
- A nested array is still an array – It just so happens that we put another array or object inside it.
2) HOW TO ACCESS A NESTED ARRAY
// (A) NESTED ARRAY
var arr = [
["Foo", "Bar"],
{ name : "Jon", gender : "M" },
text => alert(text)
];
// (B) FIRST ELEMENT - ARR[0] IS AN ARRAY
console.log(arr[0][0]); // Foo
console.log(arr[0][1]); // Bar
// (C) SECOND ELEMENT - ARR[1] IS AN OBJECT
console.log(arr[1]["name"]); // Jon
console.log(arr[1]["gender"]); // M
// (D) THIRD ELEMENT - ARR[2] IS A FUNCTION
arr[2]("TEST!"); // TEST!
When it comes to accessing a nested array, some beginners immediately go into brain freeze. No idea why. In this example:
arr[0]
is an array. So “as usual”,arr[0][0]
refers to the first element,arr[0][1]
refers to the second element.arr[1]
is an object. So “as usual”, usearr[1]["PROPERTY"]
to access it.arr[2]
is a function. So “as usual”, we call the function usingarr[2]()
.
If it is too confusing, think this way – let nested = arr[0]
. Yep, nested
is now referring to the nested array. Work on it as if it were a “flat array”.
3) NESTED ARRAY PUSH & POP
// (A) NESTED ARRAY
var arr = [
["Apple", "Banana"],
["Hello", "World"]
];
// (B) POP - REMOVE LAST ELEMENT
arr.pop();
console.log(arr); // [["Apple", "Banana"]]
// (C) PUSH - ADD ELEMENT
arr.push(["Job", "Jon"]);
console.log(arr); // [["Apple", "Banana"], ["Job", "Jon"]]
// (D) POP NESTED
arr[1].pop();
console.log(arr); // [["Apple", "Banana"], ["Job"]]
// (E) PUSH NESTED
arr[1].push("Joy");
console.log(arr); // [["Apple", "Banana"], ["Job", "Joy"]]
Nested arrays are still arrays. There’s nothing “special” about it, we can push()
and pop()
as usual. Of course, the many other functions and properties will also work – length
, splice()
, shift()
, and unshift()
.
4) LOOP OR TRAVERSE A NESTED ARRAY
// (A) NESTED ARRAY
var arr = [
["first", "second"],
["third", "forth"]
];
// (B) LOOP NESTED ARRAY
function looper (entry) {
for (let el of entry) {
if (Array.isArray(el)) { looper(el); }
else { console.log(el); }
}
};
Sadly, running through a nested array is not as simple as using a for
loop… To traverse a nested array, we will have to use a recursive function.
5) CHECK IF VALUE EXIST IN A NESTED ARRAY
// (A) NESTED ARRAY
var arr = [
["first", "second"],
["third", "forth"]
];
// (B) LOOP NESTED ARRAY
function checker (entry, find) {
let result = false;
for (let el of entry) {
if (Array.isArray(el)) {
result = checker(el, find);
} else {
if (el == find) {
result = true;
break;
}
}
}
return result;
}
var exist = checker(arr, "third");
console.log(exist); // true
Yep – If you are looking to check if a value exists in a nested array, the usual ARRAY.find()
will not quite work. We have to use a recursive function to check through all the elements again.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- Javascript Array – MDN
- JavaScript: Multidimensional Array With Push Pop – Tutsmake
- Multidimensional Array – Javascript Tutorial
- How To Flatten Arrays In Javascript – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
This is the most useful tutorial about arrays in js I’ve ever found! Thank you