V
V
Vyacheslav_Frein2021-07-03 17:54:51
JavaScript
Vyacheslav_Frein, 2021-07-03 17:54:51

Why is the arr argument equal to undefined?

As far as I understand, on the first call to reduce, the value of the arr parameter should be the second parameter of reduce. But for some reason it is equal to undefind.

function camelize(str) {
    array = str.split('-');
    console.log(array);
    let filteredArray = array.reduce((arr, item) => {
        console.log(arr);
        if(item == ''){
            return;
        }

    }, []);
}

camelize('-webkit-transition')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-07-03
@sergiks

At the first call, everything is in order, the input is an empty array.
But it is necessary to return something for the next iteration.
Now at the second call on the inputarr === undefined

spoiler
В задаче reduce, наверное, не нужен вовсе.
Я бы разбил по дефису на слова в массив: 'aBc-dEf-GH' => ['aBc', 'dEf', 'GH']
Метод массива map() пробежит по каждому элементу, возвращая новый.
Каждое слово составить заново: первую букву сделать большой, остальные маленькими: 'dEf' => 'Def'
Исключение для самого первого — там все маленькие должны быть: 'aBc' => 'abc'
function camelize(str) {
  return str.split('-')
    .map((word, i) => i ? word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase() : word.toLowerCase())
    .join('');
}

A
asmodeus13th, 2021-07-03
@asmodeus13th

You need to return an array, otherwise it will automatically return undefined.
I recommend watching this vid .

let filteredArray = array.reduce((arr, item) => {
  console.log(arr);
  if(item == ''){
    return;
  }
  return arr  // надо добавить эту строку
}, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question