Javascript Array mergeAll()

Description

Javascript Array mergeAll()


var school = [//from   w  ww .  j av  a2s  . c  o  m
  [1, 2, 3],
  [4, 5, 6, 7, 8, 3],
  [35, 3, 5]
];

Array.prototype.mergeAll = function() {
  var result = [];
  this.forEach(function(subArray) {
    result.push.apply(result, subArray);
  });
  return result;
};

var a = school.mergeAll(function(x) {
  return x;
});

console.log(a);

Javascript Array mergeAll()

Array.prototype.mergeAll = function() {
 var results = [];
 this.forEach(function(subArray) {
  subArray.forEach(function(number) {
   results.push(number);//from w w  w.  j a  v a  2s  .co  m
  });
 });
 return results;
};

var result = JSON.stringify([ [1,2,3], [4,5,6], [7,8,9] ].mergeAll());
console.log(result);
console.log(result === "[1,2,3,4,5,6,7,8,9]");
// [1,2,3].mergeAll(); // throws an error because this is a one-dimensional array

Javascript Array mergeAll()

Array.prototype.mergeAll = function() {
    var results = [];
    this.forEach(function(subArray) {
        // ------------   INSERT CODE HERE!  ----------------------------
        // Add all the items in each subArray to the results array.
        // ------------   INSERT CODE HERE!  ----------------------------
   subArray.forEach(function(element) {
    results.push(element);//from   w w  w . j  a  va2  s.c o m
   });
    });
    
    return results;
};

// JSON.stringify([ [1,2,3], [4,5,6], [7,8,9] ].mergeAll()) === "[1,2,3,4,5,6,7,8,9]"
// [1,2,3].mergeAll(); // throws an error because this is a one-dimensional array



PreviousNext

Related