Home > Enterprise >  I need to understand how the following code works. What is the step by step to get from that array t
I need to understand how the following code works. What is the step by step to get from that array t

Time:09-01

const arr = [1, 3, 1, 2, 5, 2, 3, 4, 1, 2, 3, 4, 3]
const resultado = arr.reduce((prev, cur) => ((prev[cur] = prev[cur]   1 || 1), prev), {})
//resultado = const resultado = { 1: 3, 2: 3, 3: 4, 4: 2, 5: 1,}

I am new to javascript and I need to understand how, in the following code, the array ends in an object.

CodePudding user response:

  1. Create an empty object
  2. For each element in the array:
  • Assign the value of [the object's value at thee current value plus 1, but if that doesn't exist yet return it the value of 1] to the key of the current index's value
  • Return the object so that it's available during the next iteration, and at the end for the final index

CodePudding user response:

reduce works by passing in an initial "value" to the callback which acts as the "accumulator". The accumulator will be the first argument to the callback, and the current element in the array iteration will be the second. The accumulator is passed in on each iteration.

In this simple example we're just going to add up some numbers. We pass in 0 as the initial value. This will be passed into the callback as the "accumulator" (acc). c is the current element in the iteration.

On the first iteration acc is 0. On the second iteration it is 1 (0 1. On the third iteration it is 3 (1 2) - always adding on the value of the current element, and then being passed back into the callback until there are no more elements.

const arr = [1, 2, 3, 4, 5];

const out = arr.reduce((acc, c) => {
  return acc   c;
}, 0);

console.log(out);

The example in your question follows the same logic but because it's all on one line it makes it more difficult to understand, so here it is expanded:

  1. Instead of 0 being passed in as an initial value we're passing in an empty object.
  2. If the object has a key that matches the value of the current element add 1 to that property value, otherwise initialise that property value to 1.
  3. Return the accumulator for the next iteration.

const arr = [1, 3, 1, 2, 5, 2, 3, 4, 1, 2, 3, 4, 3];

const resultado = arr.reduce((acc, c) => {
  if (acc[c]) {
      acc[c];
  } else {
    acc[c] = 1;
  }
  return acc;
}, {});

console.log(resultado);

  • Related