jsrosetta

Collections

Iterating arrays (map, filter, reduce)

Node.js's forEach, map, filter, reduce compared to Rust, Swift, and Java iterators, and hand-written generic Map/Filter/Reduce functions in Go.

Minimum versions
Node.js ≥ 12.20Go ≥ 1.18Rust ≥ 1.58Swift ≥ 4.0Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

Node.js ships forEach, map, filter, and reduce right on Array.prototype. Go's standard library has none of these for slices, but since Go 1.18 you can write them once using generics and reuse them for any data type. Rust, Swift, and Java all ship map/filter/fold (or reduce) right on their iterators/streams — no need to hand-write them like in Go; Java in particular usually collects results with collect/toList instead of Stream.reduce(), since reduce() is meant for folding down to an immutable value (like a sum), not for building up a mutable collection.

Iterating over each element (forEach)

const array = ['a', 'b', 'c']
 
array.forEach((value, i) => {
  console.log(i, value)
})
// 0 a
// 1 b
// 2 c

map, filter, reduce with generics

const mapped = array.map((value) => value.toUpperCase())
console.log(mapped) // ['A', 'B', 'C']
 
const filtered = array.filter((value, i) => i % 2 == 0)
console.log(filtered) // ['a', 'c']
 
const reduced = array.reduce((acc, value, i) => {
  if (i % 2 == 0) acc.push(value.toUpperCase())
  return acc
}, [])
console.log(reduced) // ['A', 'C']

Reference: github.com/miguelmota/golang-for-nodejs-developers#array-iteration