sasidhar
sasidhar

Reputation: 7752

Make splice or unshift return the modified array

I am recently getting accustomed to the idea of chaining the function calls and it is making my life a lot easier. But the inbuilt Array functions of JavaScript don't seem too cooperative.

How to make unshift or splice return the modified rather than the length of array and deleted items respectively? I am assuming there is a way to this with some tricky calls to call or apply.

I had to go out of my way and use concat for my use case, is there a better way of doing it?

Eg: 
 a = [2,3,4,5]
 one solution : somethingElse([1].concat(a))
 I wanted to do something like:  somethingElse(a.unshift(1));
 or may be like this: somethingElse(a.splice(0,0,1));

Upvotes: 2

Views: 1349

Answers (2)

Kirill Pisarev
Kirill Pisarev

Reputation: 843

Use grouping by parentheses, f.e. to return modified array after slice:

var a = [2,3,4,5];
somethingElse((a.splice(0,0,1), a));

Upvotes: 7

VisioN
VisioN

Reputation: 145458

One possible way is to override the original prototype methods in the following way:

var unshift = Array.prototype.unshift;
Array.prototype.unshift = function() {
    unshift.apply(this, arguments);
    return this;
};

[1, 2, 3].unshift(0);  // [0, 1, 2, 3]

Besides it is rather bad practice and you should avoid it. Instead you can create your own prototype method with unique name and use it.

Upvotes: 4

Related Questions