Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to apply multiple Array methods to an array in 1 line?

In the simple test code below I push the number 10 into an array and then splice 'hello world' into the array on the 2nd index. It works as expected.

"use strict";

let myArray = [1, 2, 3, 4, 5];

myArray.push(10);
myArray.splice(2, 0, 'hello world');

console.log(myArray);

However is it possible to do this on one line? I tried chaining in the example below and it throws an error. I can't find anyone talking about this online.

"use strict";

let myArray = [1, 2, 3, 4, 5];

myArray.push(10).splice(2, 0, 'hello world');

console.log(myArray);
like image 847
DR01D Avatar asked Jun 06 '18 19:06

DR01D


1 Answers

Yes, it is possible to do it in one line.

"use strict";

let myArray = [1, 2, 3, 4, 5];

myArray.push(10); myArray.splice(2, 0, 'hello world');

console.log(myArray);

But why do you want to do that in one line? If your concern is readability I would stick with two lines. If you want it more functional, then use a functional library

edit

I agree with what every one else said about chainability. I'm just trying to make another point

like image 79
Francesco Avatar answered Sep 25 '22 02:09

Francesco