-1

I'm trying to perform an inline split() then splice(), and it's not working.

var newValue = "61471acddbbfef00961374b5ae961943,fafd1e39db3fa20084cc74b5ae961914";
var test = (newValue.toString().split(',')).splice(0,1,'test');
console.log(test);

Output is: Array ["61471acddbbfef00961374b5ae961943"]

But I'm expecting: Array ["test","61471acddbbfef00961374b5ae961943"]

Now, if I do this:

var test = newValue.toString().split(',');
test.splice(0,1,'test');
console.log(test);

I get what I'm looking for: Array ["test","61471acddbbfef00961374b5ae961943"]

Why can't I make it all inline?: (newValue.toString().split(',')).splice(0,1,'test');

JMP
  • 4,417
  • 17
  • 30
  • 41
Zyre
  • 149
  • 1
  • 11
  • 5
    Have you read the documentation of [`Array.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)? It modifies the array in place and returns the removed elements. – axiac Jul 21 '22 at 13:51
  • `.toString()` is superfluous. `newValue` is already a string, calling `.toString()` on it is a no-op. – axiac Jul 21 '22 at 13:53
  • The second code snippet does not display `["test","61471acddbbfef00961374b5ae961943"]`. `Array.splice(0, 1, 'test')` removes `1` item starting at position `0` and puts `'test'` instead of the removed item(s). The result of `test.splice(0,1,'test')` is ['test', 'fafd1e39db3fa20084cc74b5ae961914']`. – axiac Jul 21 '22 at 13:57
  • 1
    @axiac, you're absolutely right.. "Return value: An array containing the deleted elements."... I was so caught up in what I assumed it returned I didn't read the documentation in full. Totally my mistake. Thank you for pointing it out and it all makes sense to me now why it wasn't giving me the result I was looking for... – Zyre Jul 21 '22 at 14:08

1 Answers1

0

If you absolutely need it as an oneliner, you can do it with concat and slice.

var str = "a,b,c";
var test = ['test'].concat(str.split(',').slice(0, 1));

console.log(test);
// output: [ "test", "a" ]
tom
  • 9,550
  • 6
  • 30
  • 49