Simple Javascript Nested Array Examples – Create Push Pop Loop Check

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 Array Yoga Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

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

1-create-nested.html
// (A) NESTED ARRAY
var arr = [
  // FIRST - STRING
  "Foo Bar",
  // SECOND - NUMBER
  123,
  // THIRD - BOOLEAN
  true,
  // FORTH - ARRAY
  ["Hello", "World"],
  // FIFTH - OBJECT
  { name : "Jon", gender : "M" },
  // SIXTH - FUNCTION
  (text) => { console.log(text); }
];

// (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) => { console.log(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

2-access-nested.html
// (A) NESTED ARRAY
var arr = [
  ["Foo", "Bar"],
  { name : "Jon", gender : "M" },
  (text) => { console.log(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”, use arr[1]["PROPERTY"] to access it.
  • arr[2] is a function. So “as usual”, we call the function using arr[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

3-push-pop-nested.html
// (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

4-loop-nested.html
// (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

5-check-exist.html
// (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.

 

 

USEFUL 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

 

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!

1 thought on “Simple Javascript Nested Array Examples – Create Push Pop Loop Check”

Leave a Comment

Your email address will not be published. Required fields are marked *