3

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;
        }

    }
});
1
  • Maybe try the splice method. Commented Nov 19, 2013 at 23:57

1 Answer 1

7

You mean .filter?

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

var after = before.filter(function (item) { return item.keep; }).map(function (item) { return { z: item.a }; }) That was exactly it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.