Question

I have a JavaScript example with map reduce to remove items from an array, after transforming them. Is there a simpler method to achieve this as it seems a bit complicated

I put it in a JSFiddle here and here is the map reduce part:

var after = before.map(function (item) {
    if (item.keep) {
        return {
            z: item.a
        };
    } else {
        return undefined;
    }
}).reduce(function (prev, item) {
    if (item) {
        if ($.isArray(prev)) {
            prev.push(item);
            return prev;
        } else if (prev) {
            return [prev, item];
        } else {
            return [item];
        }
    } else {
        if ($.isArray(prev)) {
            return prev;
        } else if (prev) {
            return [prev];
        } else {
            return prev;
        }

    }
});
Was it helpful?

Solution

You mean .filter?

var after = before.filter(function (item) {
   return item.keep;
});

Then you can still .map it if you want/need to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top