I have an array of fruits. I want to construct a ma separated string of this array for first three elements only. Right now, I am constructing a ma separated string for all.
var fruits = [];
fruits.push("Banana");
fruits.push("Orange");
fruits.push("Apple");
fruits.push("Mango");
fruits.push("Orange");
fruits.push("Papya");
fruits.push("CALAPPLE");
var result = fruits.toString();
alert(result);
Could you please let me know how to achieve this? This is my jsfiddle.
I have an array of fruits. I want to construct a ma separated string of this array for first three elements only. Right now, I am constructing a ma separated string for all.
var fruits = [];
fruits.push("Banana");
fruits.push("Orange");
fruits.push("Apple");
fruits.push("Mango");
fruits.push("Orange");
fruits.push("Papya");
fruits.push("CALAPPLE");
var result = fruits.toString();
alert(result);
Could you please let me know how to achieve this? This is my jsfiddle.
Share Improve this question edited Jun 7, 2015 at 15:18 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Jun 7, 2015 at 14:42 PawanPawan 32.4k109 gold badges268 silver badges447 bronze badges 01 Answer
Reset to default 8Slice the array with Array.prototype.slice
, which will return a new array with only the sliced elements and join them with Array.prototype.join
, like this
console.log(fruits.slice(0, 3).join(", "));
// Banana, Orange, Apple
Here, we say that start slicing from index zero, till three. The last element will not be included in the slice. So, from the index zero, we get the elements at index zero, one and two.
If you don't want to create a new array with slice
, you can just use a simple for
loop and do it like this
var result = "";
for (var i = 0; i < 2; i += 1) {
result += fruits[i] + ", ";
}
result += fruits[i];
console.log(result);
// Banana, Orange, Apple