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));
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));
Share
Improve this question
edited Apr 11, 2017 at 8:36
halfer
20.4k19 gold badges109 silver badges202 bronze badges
asked Jan 15, 2015 at 12:01
sasidharsasidhar
7,76216 gold badges51 silver badges78 bronze badges
2
-
call
andapply
can change the way the functions are called, they cannot change the return values of the functions. – thefourtheye Commented Jan 15, 2015 at 12:07 -
Yeah, but I was wondering someway we can get this functionality. Its kind of sad that we cannot chain it like this for the power of functions like
splice
too good to loose. – sasidhar Commented Jan 15, 2015 at 12:08
2 Answers
Reset to default 7Use grouping by parentheses, f.e. to return modified array after slice:
var a = [2,3,4,5];
somethingElse((a.splice(0,0,1), a));
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.