Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Array from startIndex to endIndex

I wanted to ask if there is some kind of utility function which offers array joining while providing an index. Maybe Prototype of jQuery provides this, if not, I will write it on my own :)

What I expect is something like

var array= ["a", "b", "c", "d"];
function Array.prototype.join(seperator [, startIndex, endIndex]){
  // code
}

so that array.join("-", 1, 2) would return "b-c"

Is there this kind of utility function in an pretty common Javascript Library?

Regards
globalworming

like image 960
globalworming Avatar asked Apr 26 '12 23:04

globalworming


2 Answers

It works native

["a", "b", "c", "d"].slice(1,3).join("-") //b-c

If you want it to behave like your definition you could use it that way:

Array.prototype.myJoin = function(seperator,start,end){
    if(!start) start = 0;
    if(!end) end = this.length - 1;
    end++;
    return this.slice(start,end).join(seperator);
};

var arr = ["a", "b", "c", "d"];
arr.myJoin("-",2,3)  //c-d
arr.myJoin("-") //a-b-c-d
arr.myJoin("-",1) //b-c-d
like image 121
muffel Avatar answered Oct 12 '22 03:10

muffel


Just slice the array you want out, then join it manually.

var array= ["a", "b", "c", "d"];
var joinedArray = array.slice(1, 3).join("-");

Note: slice() doesn't include the last index specified, so (1, 3) is equivalent to (1, 2).

like image 21
Elliot Bonneville Avatar answered Oct 12 '22 02:10

Elliot Bonneville