Skip to content Skip to sidebar Skip to footer

Concat Arrays Into Array Javascript

I have a function that has an array with the months of the year. In my function i delete some words of the month name. My function is The result is ['Ene'] ... ['Dic'] But i want

Solution 1:

Problem:

In OP code, the statement

var result = [array[i].slice(0, 3)];

is creating a variable result in each iteration of the for loop and assigning an array having one element in it, so after loop finishes execution, the result variable will only contain the last element ["Dic"].

Answer :

To add the elements to array, use Array#push.

var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

// Declare new empty arrayvar result = [];

// Loop over main arrayfor (var i = 0; i < array.length; i++) {
  // Add the new item to the end of the result array
  result.push(array[i].slice(0, 3));
}
console.log(result);

Use Array#map

var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

var months = array.map(function(e) {
  return e.substr(0, 3);
});
console.log(months);

Solution 2:

Have result be an empty array and push() to it.

var result = [];
var array = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
for(var i=0; i<array.length; i++){
   result.push(array[i].slice(0,3));
}
console.log(result);

Solution 3:

The slice() method returns the selected elements in an array, as a new array object. - http://www.w3schools.com/jsref/jsref_slice_array.asp

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. - http://www.w3schools.com/jsref/jsref_substr.asp

Post a Comment for "Concat Arrays Into Array Javascript"