3

I have a small issue with understanding why I'm getting this output.

var arr = ["a", "b", "c", "d", "e", "f"];
arr.splice(2,0,"1");
console.log(arr);  

var arr2 = ["a", "b", "c", "d", "e", "f"];
arr2 = arr2.splice(2,0,"2");
console.log(arr2);

ouput is:

[ 'a', 'b', '1', 'c', 'd', 'e', 'f' ]
[]  

Why is the second line of output not:

[ 'a', 'b', '2', 'c', 'd', 'e', 'f' ]  

Is it an issue of assignment or what?

Moolla
  • 169
  • 1
  • 7

3 Answers3

7

Reading about splice method. It returns

An array containing the removed elements. If only one element is removed, an array of one element is returned.

So by doing

arr2 = arr2.splice(2,0,"2");

you overwrite initial array arr with empty array [] returned by splice.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Totally didn't see this answer. Wouldn't have posted a duplicate otherwise. :) – techfoobar May 05 '13 at 07:46
  • So, is it not possible to chain .split() and .splice()? If we have `var str = "12345";` in order to output: `["1", "2", "a", "3", "4", "5"]`do we have to do: `var arr = str.split(""); arr.splice(2,0,"a"); return arr;`? Why can't we use `arr = str.split("").splice(2,0,"a");` – Moolla May 05 '13 at 08:05
  • @Moolla No, you can't chain them like this, since `splice` does not return the first array. – dfsq May 05 '13 at 08:10
2

1 - The splice method Changes the content of an array

2 - The splice method returns the element removed - ** Not original Array **

Ahmed Alnahas
  • 263
  • 1
  • 4
0

So the problem is that only some methods return the original object after mutation as the return value. You can use a method decorator to keep access to the original object available even when the methods are designed differently.

const chainer = (target) =>
  new Proxy(target, {
    get: (_, prop, receiver) =>
        typeof target[prop] === 'function'
        ? new Proxy(target[prop], {
            apply: (f, _, args) => {
              f.apply(target, args);
              return {
                this: receiver,
                target,
              }
            },
          })
        : target[prop],
  });

const arr2 = chainer(["a", "b", "c", "d", "e", "f"])
    .splice(2,0,"1").this
    .splice(2,0,"2").target;
console.log(arr2);
loop
  • 825
  • 6
  • 15