UnKnown UnKnown - 23 days ago 6
jQuery Question

How to write a Utilily function which returns all elements in an array after 2 elements

I am trying to write a utility which fetches all elements of an array after 2 elements

I have tried it this way but i am getting undefined

// ARRAYS
var arr = ['one', 'two', 'three', 'four', 'five'];

var valuefromutility = getcommasperatedvalue(arr);
console.log(valuefromutility);

function getcommasperatedvalue(arr)
{
var arrayafter3elemnts = '';
for (var i = 0; i < arr.length; i++)
{
if (i > 2)
{
if (i === arr.length - 1)
{
arrayafter3elemnts += arr[i];
}
else
{
arrayafter3elemnts += arr[i] + ',';
}
}
}
}


http://jsfiddle.net/cod7ceho/336/

Answer

To fetch all elements after the first 2 elements, use Array.prototype.slice

function getcommasperatedvalue(arr) {
    return arr.slice(2).join(',');
}

var arr = ['one', 'two', 'three', 'four', 'five'];
console.log(getcommasperatedvalue(arr));