Kasper Kasper - 2 months ago 7
Javascript Question

Join a part of the array and leaving the rest as is in Javascript

I have an array, and I want to join from some beginIndex to some endIndex, and leave the rest as is.

For example, I have this array:

['first', 'second', '<error>', 'Can not parse the third element', '</error>', 'fourth', 'fifth']


And I want to
join('\n')
the elements from index 2 until index 4. So that I get:

['first', 'second', '<error>\nCan not parse the third element\n</error>', 'fourth', 'fifth']


Any suggestions?

Edit: Wow, thanks for the 4 downvotes and 2 close votes for this innocent well formulated question. Yes, I got something that worked with a for of loop, but I found it ugly, and I was looking for something more elegant, I didn't know about the splice method. Thanks Soviut and Nina for the interesting answers. Hope that other people with the same question can learn from it as well...

Answer

You could use Array#splice

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

var array = ['first', 'second', '<error>', 'Can not parse the third element', '</error>', 'fourth', 'fifth'],
    beginIndex =2,
    endIndex = 4;

array.splice(beginIndex, 0, array.splice(beginIndex, endIndex - beginIndex + 1).join('\n'));

console.log(array);

Comments