agonzalezmc
agonzalezmc

Reputation: 113

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

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

for (var i = 0; i < array.length; i++) {
  var result = [array[i].slice(0, 3)];
  console.log(result);
}

The result is ["Ene"] ... ["Dic"] But i want have some like this: ["Ene", ... , "Dic"] How i can concat the result in a unique array?

Upvotes: 1

Views: 256

Answers (3)

Tushar
Tushar

Reputation: 87203

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"].

Solution:

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 array
var result = [];

// Loop over main array
for (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);

Upvotes: 3

Suciu Sergiu
Suciu Sergiu

Reputation: 59

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

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

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);

Upvotes: 0

Related Questions