Search code examples
javascriptsubstringreduce

Get length of word array using reduce and substring method


I try to get the number of characters without taking into account the last two positions of the word.

I have the following array:

let arrayWords = ["comput3r-9", "b0dywork-7", "e4rth-1"];

but when using the reduce and substring method on the first word: "comput3r-9", the method is not applied

let arrayWords = ["comput3r-9", "b0dywork-7", "e4rth-1"];
let getTotalCharacters = (x) => x.reduce(
    (prev, curr) => (prev + curr.substring(0, curr.length-2))
);

console.log(getTotalCharacters(arrayWords).length);


Solution

  • You forgot to add an initial value for the accumulator. It should be an empty string here:

    let arrayWords = ["comput3r-9", "b0dywork-7", "e4rth-1"];
    let getTotalCharacters = (x) => x.reduce(
      (prev, curr) => (prev + curr.substring(0, curr.length - 2)),
      "",
    );
    
    console.log(getTotalCharacters(arrayWords).length);

    If you don't pass an initial value, the accumulator will start with the value of the first element and the callback will skip over the first element, which is why it doesn't process the first element in your example.