How to append items to nested array in JavaScript

javascript multidimensional array of objects
javascript multidimensional array push
javascript push array into array
javascript array of objects
javascript foreach multidimensional array
add object to array of objects javascript
add items to 2d array javascript
how to create nested array in javascript

I have an outer JS array 'main_category' which should contain several arrays within it called 'temp'.

The array temp contains several string elements taken from an li tag.

In order to populate both the arrays I am running a for-loop through each li tag for each ul tag in the html page, as shown below:

function a{
   var category_list = [];
   var temp;

   //how to split this list iteration into two for-loops
   $(".ul_list li").each(function(){
       temp = [];
       //adding only those list elements of a ul, that are red in color
       if($(this).attr("style") == "color:red"){
          var cat = $(this).text();
          cat = cat.replace(/\s\s+/g, ' '); //removes whitespaces
          temp.push(cat); //creates a single array for a single element
       }
    }
    category_list.push(temp);  
   });
 }

Desired output:

  category_list = [['l1', 'l2', 'l3'], ['l1', 'l2', 'l3'], ['l1', 'l2', 'l3']..]

Current output:

   category_list = [['li'], ['l2'], ['l3']...]

However, the temp.push(cat) LOC creates a temp array for each individual li element instead of creating a temp=[] for all the li elements within one ul.

You can do this through iterating through each .ul_list element then their children in that order should give you the expected result.

function a() {
	let list = []
	$(".ul_list").each(function() {
		let temp = []
		$(this).children().each(function() {
			let text = $(this).text()
			text.replace(/\s\s+/g, ' ')
			temp.push(text)
		})
		list.push(temp)
	})
	return list
}

console.log(a())

5 Way to Append Item to Array in JavaScript, (JavaScript array indexes start at zero.) Adding and Removing Elements in Multidimensional Arrays. You can use square bracket notation to add elements to the� The push() method adds new items to the end of an array, and returns the new length. Note: The new item(s) will be added at the end of the array. Note: This method changes the length of the array. Tip: To add items at the beginning of an array, use the unshift() method.

The following will map each ul to an array, and all the lis in each ul to an array, so it will be a 2 dimensional array, where each category_list[#] is a ul and the sub array is each li's text you modified.

function a() {
  var category_list = $('.ul_list').get().map(function(ul){
    return $('li', ul).get().map(function(li){
      return $(li).text().replace(/\s\s+/g, ' '); //removes whitespaces
    });
  });
  
  console.log(category_list);
}

a();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="ul_list">
  <li>1 Thing</li>
  <li>2 Thing</li>
  <li>3 Thing</li>
</ul>

<ul class="ul_list">
  <li>4 Thing</li>
  <li>5 Thing</li>
  <li>6 Thing</li>
</ul>

JavaScript Multidimensional Arrays, How to use JavaScript push, concat, unshift, and splice methods to add elements to the end, beginning, and middle of an array. How to Append an Item to an Array in JavaScript. In this tutorial, you will find out the solutions that JavaScript offers for appending an item to an array. Imagine you want to append a single item to an array. In this case, the push() method, provided by the array object can help you. So, it would be best if you act as follows:

Maybe a bit over simplified but I got the desired output. https://jsbin.com/tofimik/edit?html,js,console,output Step 1. declare empty array Step 2. run your loop, get all children in your ul element Step 3. Turn each collection of children into an array Step 4. Push child collection into new array

  var temp = []
  var cat;
  $('ul').each(function(){
    cat = []
    var liTags = Array($(this).children().text().trim());
    temp.push(liTags);
  })

How to Add Elements to an Array in JavaScript, You can use the Array methods such as push() and splice() to manipulate elements of a multidimensional array. For example, to add a new element at the end of� In previous tutorials we’ve taken a look at JavaScript array basics, manipulating arrays, and sorting arrays.So far, all the arrays we’ve dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object.

(Posted the solution on behalf of the question author).

This solution was provided by James_F:

   function a{
     let category_list = [];

     $(".ul_list").each(function(){
       let temp = [];
       $(this).children().each(function(){
          //adding only those list elements of a ul, that are red in color
          if($(this).children().attr("style") == "color:red"){
             var cat = $(this).text();
             cat = cat.replace(/\s\s+/g, ' '); //removes whitespaces
             temp.push(cat); //creates a single array for a single element
          }
       })
       category_list.push(temp);
     })
   }

Learn JavaScript Multidimensional Array By Examples, So far, all the arrays we've dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object. # 2 Ways to Append Item to Array (Non Mutative) Alright, let's move on to appending an item to an array in a non mutative way. Where the original array will remain untouched and a new array will contain the addition. # concat. This method is meant to merge arrays. So we can use it to add multiple items by passing in an array.

Nested Arrays in JavaScript, Append the element to the end of the array: let fruits We can use it for multidimensional arrays, for example to store matrices: let matrix = [ [ 1� You could iterate the array and test if _id property has the wanted value. Then save either the node, the parent or the next item of the array. For getting the parent node, the actual parent is saved as a closure and returned if the wanted _id is found. All functions test for subItems as array and if, it performs an iteration over subItems.

Arrays, This includes arrays and array-like constructs such as Array objects and Alternatively, create an empty array first before adding the single element to it. Arrays can be nested, meaning that an array can contain another� Climb and append nested objects/array I am trying to understand how to recursively append a branching structure to an object. I am trying to append children to an empty JSON object that when built out should look like the following.

Indexed collections, Create and access values in two dimensional arrays; Understand real-world use Multidimensional arrays are a special kind of nested data structure, which toLowerCase())) { return ++count; // add 1 to count then return the value (this is� Amazon Wishlist Watcher Anchor <•> used for Debugging purposes only *Variable Set [ Name:%DEBUG To:true Recurse Variables:Off Do Maths:Off Append:Off Max Rounding Digits:3 ] Anchor <•> If [ %DEBUG Set ] Array Clear [ Variable Array:%Current_Title ] Array Clear [ Variable Array:%Current_Price ] Array Clear [ Variable Array:%Previous_Title

Comments
  • Are there multiple .ul_list? Also it looks like an invalid function definition for function a(){}
  • You push temp to the category array in a scope where temp is not defined. The expression category_list.push(temp) needs to be moved one line up.
  • @Taplar yes there are 12-15 .ul_list in the html template. No the function is being invoked successfully on the button click
  • The .ul_list li will select a flat list of <li> elements. The elements will not get magically grouped by their parent <ul> element.
  • Can you provide sample of input and desired output, as well as the output that you are actually getting?
  • This code is only creating an array with all li elements within it. It is not creating a sub-array for li elements belonging to one particular ul
  • The outer map is on the ul. The inner map is on the li's for the ul. You're saying this is not working? @Simran
  • Yes its creating a single Array(45) of 45 elements, i.e for a total of 5 list items * 9 lists
  • Weird, for some reason it was flattening it. Modified it, and included a runnable snippet to show it works.