DEV Community

Discussion on: Array manipulation in JavaScript 🧐

 
rokkoo profile image
Alfonso

Truly reasons, I'm a junior developer and I'm used to using these methods because they are easy to use and their implementation too.
In countable occasions, I need to work in low-level loops to search optimization of code.
Thanx for sharing your knowledge it has been helpful and this babel package.

Thread Thread
 
qm3ster profile image
Mihail Malo • Edited

Writing it by hand it would probably look something like this:

let sumOfDoubles = 0
for (let i = 0; i < numbers.length; i++) {
  const num = numbers[i]
  if(Number.isInteger(num))
    sumOfDoubles += num * 2
}

But if you are writing application code with a framework, and not making your own library, you will probably have better returns if you look at your algorithms and data structures. It's very rare to be limited by loop performance in a frontend application.
If your collection is like 10 items, and your filtering and mapping predicates are complicated, there's usually no shame in applying a filter and then a map separately.

Thread Thread
 
mdor profile image
Marco Antonio Dominguez • Edited

I agree depends on the case, some of the issues are related to maintainability other to performance issues, most of the cases is because some people is trying to overcomplicate things because some imaginary scalability issues.

Despite the fact the code is more performant, we should consider:
1 - Number of items
2 - Amount of operations
3 - Think in the different benefits coming from different worlds, FP, OOP, etc.

I saw more issues coming from extremely premature optimizations than performance issues, even with large datasets...

In addition, the code can be even readable

// example 1
const total = numbers.reduce((t, c) => t + (!Number.isInteger(c) ? 0 : (c*2)), 0);

// Example 2
let acc = 0;
for (let i = 0, size = numbers.length; i < size; i++) {
  const cur = numbers[i]
  acc += (!Number.isInteger(cur) ? 0 : (cur * 2));
}

// Example 3
const total = numbers
  .filter(cur => !!cur && Number.isInteger(cur))
  .reduce((t,c) => (t + c* 2), 0)
  // We clean up the falsy values (including 0), and we avoided another iteration

Again, it depends on the conditions,