1

I am just learning javascript.I am pretty confused with manipulating multidimensional arrays.

var myarr = [ 
       [ 7, 9, 10 ], 
       [ 6, 9 ], 
       [ 5, 9 ] 
  ]

I want to insert zero like this.What is the smart way to do this in javascript

       [ 
           [ 7, 9, 10 ], 
           [ 6, 9, 0 ], 
           [ 5, 9, 0 ] 
       ]
6
  • You want to insert zeros dynamically? How many? A zero per array? Commented Oct 17, 2016 at 12:32
  • 1
    If you have your implemented code, can you please post it ? Commented Oct 17, 2016 at 12:33
  • No just insert zero like I mentioned.I am using this array to do matrix calculations Commented Oct 17, 2016 at 12:34
  • 1
    first find the maximum array length then loop through the array and insert required zeros Commented Oct 17, 2016 at 12:35
  • 1
    @Nane: You should always include your efforts in your question. This advice is also aimed at whoever the 3 upvoters are! Commented Oct 17, 2016 at 12:50

8 Answers 8

2

You could get first the max length of the inner arrays and push zeroes until all inner arrays have the same length.

var myarr = [[7, 9, 10], [6, 9], [5, 9]],
    length = myarr.reduce(function (r, a) { return Math.max(r, a.length); }, 0);

myarr.forEach(function (a) {
    while (a.length < length) {
        a.push(0);
    };
});

console.log(myarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0
var myarr = [ 
       [ 7, 9, 10 ], 
       [ 6, 9 ], 
       [ 5, 9 ] 
  ]

for(var i = 0; i < myarr.length; i++) {    
    if(myarr[i].length < myarr.length){
       myarr[i].push(0);
    }
}

console.log(myarr);

2 Comments

Its working just update your answer by replacing num 3 with myarr.length coz that's what i expected
This solution seems a bit limited, it might work for this input but other input will fail. For example, you are assuming the longest length will match the number of sub-arrays. Also, you assume there will only ever be 1 missing element at most for each sub-array.Try this input to see what I mean: [1, 2, 3], [1], [1, 2], [1, 2]
0

Here is a solution.

var myarr = [
  [7, 9, 10],
  [6, 9],
  [5, 9]
];

var rows = myarr.length;
var cols = 0;

for (var i in myarr) {
  if (myarr[i].length > cols)
    cols = myarr[i].length;
}

for (i = 0; i < rows; i++) {
  for (j = 0; j < cols; j++) {
    if (myarr[i][j] == undefined)
      myarr[i][j] = 0;
  }
}

console.log(myarr);

Comments

0

Best way would be first to calculate what the longest sub-array length you have, then you can pad the sub-arrays to make them all up to the same length.

The following includes a function for calculating the longest length, and another for performing the padding:

function getMax(arr) {
  var max = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].length > max)
      max = arr[i].length;
  }
  return max;
}

function pad(arr, max) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = arr[i].length; j < max; j++)
      arr[i].push(0);
  }
}

var myarr = [
  [7, 9, 10],
  [6, 9],
  [5, 9]
];

pad(myarr, getMax(myarr));

console.log(myarr);

Comments

0

Seems like you need a square matrix from a 2 dimension array, so try this:

var myarr = [
  [7, 9, 10],
  [6, 9],
  [5, 9, 1, 2, 3, 4, 5, 6, 7] // <--- for example purpose
];

var rows = myarr.length;
var cols = 0;

for(var i = 0; i < myarr.length; i++){
  if(myarr[i].length > cols)
    cols = myarr[i].length;
}

var limit = rows > cols ? rows : cols;
for(var i = 0; i < limit; i++){
  if(myarr[i] == undefined)
    myarr[i] = new Array(limit);
  for(var j = 0; j < limit; j++){
    if(typeof myarr[i][j] == "undefined")
      myarr[i][j] = 0;
  }
}

for(var i = 0; i < limit; i++){
  console.log(JSON.stringify(myarr[i]));
}

Comments

0
var maxLength=0;
for(var i=0;i<myarr.length;i++){
   if(myarr[i].length>maxLength){
      maxLength=myarr[i].length
  }
}
for(var i=0;i<myarr.length;i++){
    if(myarr[i].length!=maxLength){
    fillZeros(myarr[i])
    }
  }
function fillZeros(child){
    while(child.length!=maxLength)
     {child.push(0);}
}

1 Comment

I appreciate the efforts for keeping the internet storage footprint down! ...but seriously, not very readable is it..
0

If your array is a numbers only arbitrarily nested filled array, you could use a recursive function like I have here:

function fillArray(array,  val){

  for(var i=0; i<array.length; i++){    
    if(typeof(array[i]) === 'number'){
        array[i] = val;
    }else{
        fillArray(array[i],  val);
    }
  } 

}
var test = [5,[3,8,-1,[3,4,5,2,1],[2] ],[[2,2],[3]],[[2,3],[4]],[[2,4],[5]]];
fillArray(test, 0);

Comments

-1

using map function

var arr = [ 
           [ 7, 9, 10 ], 
           [ 6, 9], 
           [ 5, 9] 
       ]

       var arr1 = arr.map(function(e){
       var arr2 = [];
        if(e.length < 3)
            e.push(0);

         arr2.push(e);
         return arr2;

       });

      alert(arr1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.