Substring issue when combined with map or reduce. Am I doing something wrong?

37 Views Asked by At

According to spec, when a second argument is omitted, substring should return n characters from the end of the string.

If embedded in an array map or reduce, substring with a single argument seems to do nothing.

I have tried the following in both nodejs and in the browser console (firefox), however get "incorrect" output:

let a = [["g9qleb3ycfzs2rgrqebjtqol",1],["amjjvjvz3d7hvl7eu9k9alfj",1]]

let b = a.reduce((p,[x, y]) => [ ...p, [ x.substring(1), y ] ],[])
let c = a.map(([x, y]) => [ x.substring(1), y ]);

// Expected: [["l",1],["j",1]]
// Received: [["g9qleb3ycfzs2rgrqebjtqol",1],["amjjvjvz3d7hvl7eu9k9alfj",1]]
console.log(b) 

// Expected: [["l",1],["j",1]]
// Received: [["g9qleb3ycfzs2rgrqebjtqol",1],["amjjvjvz3d7hvl7eu9k9alfj",1]]
console.log(c) // should return: [["l",1],["j",1]]

When I use two arguments for the substring method (e.g. to return first value of string), it works as expected:

let a = [["g9qleb3ycfzs2rgrqebjtqol",1],["amjjvjvz3d7hvl7eu9k9alfj",1]]

let b = a.reduce((p,[x, y]) => [ ...p, [ x.substring(0,1), y ] ],[])
let c = a.map(([x, y]) => [ x.substring(0,1), y ]);

// Expected: [["g",1],["a",1]]
// Received: [["g",1],["a",1]]
console.log(b) 

// Expected: [["g",1],["a",1]]
// Received: [["g",1],["a",1]]
console.log(c) // should return: [["l",1],["j",1]]

Does anyone have any insight to this?

0

There are 0 best solutions below