Skip to content Skip to sidebar Skip to footer

Do Javascript Arrays Have A Chainable Method Similar To Foreach?

In a chain of array manipulation methods, I'd like to alter a property of each item in the array. Each of the available methods has a problem when used this way: Array.prototype.

Solution 1:

No, there is no such method. Common helper libraries (Underscore, jQuery, Prototype, …) do have each iteration methods that return the array, though.

The forEach method does not return the original array because it is not made for functional chaining, but for executing side effects.

The map method is the tool of choice here. It comes from functional programming, and its purpose is to create a new array of transformed objects, which is naturally returned from the function. By mutating your objects instead of creating new ones, you were disregarding this paradigm, but you can still use it when you return the (mutated) objects.

Solution 2:

Have you considered reduce?

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

var items = [
   { name: 'Smith' }, 
   { name: 'Jones' }, 
   { name: 'Simpson' }
];

items.reduce(function (memo, item) {

    item = 'Sir ' + item + ', the first.';

    if (somePredicate(item)) {
        memo.push(item);
    }

    return memo;

}, []);

Post a Comment for "Do Javascript Arrays Have A Chainable Method Similar To Foreach?"