Simple Javascript Nested Array (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!

 

 

TABLE OF CONTENTS

 

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 = [
  "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

2-access-nested.html
// (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”, 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.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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

 

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 (Create Push Pop Loop Check)”

Leave a Comment

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