I have the code
const walk = ['n','s','n','s','n','s','n','s','n','s']
let object ={}
walk.filter(elem=>elem =='n').reduce((acc,item)=>{
object["north"] = ++acc
return acc++
},0)
walk.filter(elem=>elem =='s').reduce((acc,item)=>{
object["south"] = ++acc
return acc++
},0)
here I iterate through the array and write the direction of movement to the object. Is it possible to somehow simplify the expressions? for example use 1 reduce. It seems to me that it can be done without two filter and reduce, but I don’t quite understand how. I write this data into an object, with the number of times it turns in a certain direction
you can simply iterate through forEach, but I wanted to practice reduce, although it’s not relevant here
5
Answers
You could take the direction as ke for getting a total for every direction.
you can simplify the code by using a single reduce function to count the occurrences of each direction in the walk array. Here’s how you can do it.
use a single reduce function to iterate through the walk array. We initialize an empty object as the initial accumulator ({}), and for each direction encountered, we update the count in the object. The acc[direction] = (acc[direction] || 0) + 1 line ensures that we increment the count for each direction in the object, and if the direction hasn’t been encountered before, it initializes it to 1.
Here, the reduce function iterates through the walk array, and for each direction encountered, it updates the object with the count of that direction. The acc (accumulator) starts as an empty object {}. If the direction is ‘n’, it increments the "north" count in the object, and if the direction is ‘s’, it increments the "south" count.
This way, you achieve the same result with a single reduce operation and avoid the need for separate filter and reduce operations.
Inside the
.reduce
callback you check for the value of the current itemand assign accordingly to the accumulator.
In the second parameter of
.reduce
we pass the initial valueof the accumulator to start at 0 each direction.