333

I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:

function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });   
}

Is that a good approach? Is there a better method? I'm open to use any library such as lodash.

3

18 Answers 18

421

You should use Array.reduce for this.

var options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

var reduced = options.reduce(function(filtered, option) {
  if (option.assigned) {
     var someNewValue = { name: option.name, newProperty: 'Foo' }
     filtered.push(someNewValue);
  }
  return filtered;
}, []);

document.getElementById('output').innerHTML = JSON.stringify(reduced);
<h1>Only assigned options</h1>
<pre id="output"> </pre>


Alternatively, the reducer can be a pure function, like this

var reduced = options.reduce(function(result, option) {
  if (option.assigned) {
    return result.concat({
      name: option.name,
      newProperty: 'Foo'
    });
  }
  return result;
}, []);
7
  • 5
    For me, the first arg, filtered is an object. so filtered.push is undefined for me. Jan 4, 2018 at 10:26
  • 11
    I also had an issue with filtered being an object. This was because I wasn't passing in the "initial value" - the empty array ([]) after the reduce function. e.g. incorrect var reduced = options.reduce(function(filtered, option) { ... }); correct var reduced = options.reduce(function(filtered, option) { ... }, []); Feb 7, 2018 at 3:39
  • 1
    @Marko I introduced a pure reducer as well. PTAL. Jul 24, 2019 at 7:23
  • 1
    Yap that is pure now. +1 for your effort. Not that I'm pure functional programming advocate, far from that, I just couldn't see the point :) But actually I have used your trick after seeing it, because it came so handy in the given situation. But for this task you might want to take a look at flatMap function, I think it came into standard after you made your answer (also for that reason may be unsupported by some browsers). It should be more performant since concatenating arrays like this makes O(n^2) task out of O(n) task.
    – Marko
    Jul 24, 2019 at 9:46
  • 1
    @Marko flatMap cannot be used here, as it would not allow us to filter. Unless, we return an empty array in that case. That would not make things easy for the reader I believe. Jul 24, 2019 at 10:11
190

Since 2019, Array.prototype.flatMap is good option.

options.flatMap(o => o.assigned ? [o.name] : []);

From the MDN page linked above:

flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

5
  • 3
    How does this compare in term of performance to using 2 loops (by calling array.filter and array.map individually)?
    – Simon Tran
    Sep 13, 2021 at 5:04
  • 1
    I compared using jsbench.me and jsben.ch and got very different results. First time flatMap was like 5 times slower, second time it was like 2 times faster. So I don't know how to benchmark it. Sep 13, 2021 at 9:31
  • 4
    Maybe it's because I have more OO experience, but this answer seems more intuitive than reduce to me. Sep 7, 2022 at 6:50
  • body.files.flatMap(file => file?.file ?? []) // can be cleaner if you don't need a ternary
    – Stefan T
    Apr 5 at 21:16
  • 1
    Even nicer with ES6 destructuring: options.flatMap(({assigned, name}) => assigned ? [name] : []);
    – davetapley
    Aug 25 at 23:04
70

With ES6 you can do it very short:

options.filter(opt => !opt.assigned).map(opt => someNewObject)

4
  • 3
    @hogan but this is the correct answer ( may not be optimal solution ) to the original query
    – vikramvi
    Jun 27, 2019 at 9:24
  • 1
    @vikramvi thank you for your note. The thing is, we can achieve the same things with tons of ways and I´d prefer the best one.
    – hogan
    Jun 28, 2019 at 10:14
  • 3
    This is not entierly correct, because here you are loosing the index in which the values where initialy positioned, and that information can be really useful when running the map fn. Aug 7, 2020 at 22:03
  • 3
    this way is good but this question is Map and filter an array at the same time best way is options.reduce(res,options.... answer @Zuker Nov 16, 2021 at 8:13
62

Use reduce, Luke!

function renderOptions(options) {
    return options.reduce(function (res, option) {
        if (!option.assigned) {
            res.push(someNewObject);
        }
        return res;
    }, []);   
}
0
21

I'd make a comment, but I don't have the required reputation. A small improvement to Maxim Kuzmin's otherwise very good answer to make it more efficient:

const options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

const filtered = options
  .reduce((result, { name, assigned }) => assigned ? result.push(name) && result : result, []);

console.log(filtered);

Explanation

Instead of spreading the entire result over and over for each iteration, we only append to the array, and only when there's actually a value to insert.

2
  • 1
    .concat() returns a new array, it's effectively the same as spreading the old array and new item into a new array, MDN here. You want to use .push() to "append" as you described.
    – MarceDev
    May 26, 2021 at 4:20
  • @MarceDev ah you're right, thanks. Will update my answer to do that. The syntax then becomes a little bit weird because push does not return the array.
    – matsve
    Jun 30, 2021 at 13:05
20

One line reduce with ES6 fancy spread syntax is here!

var options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

const filtered = options
  .reduce((result, {name, assigned}) => [...result, ...assigned ? [name] : []], []);

console.log(filtered);

3
  • 2
    Really nice @Maxim! I upvote this! But... on each element added, it has to spread all elements in result... is like filter(assigned).map(name) solution
    – 0zkr PM
    Sep 25, 2018 at 20:31
  • 4
    Nice one. It took me a sec to realise what was going on with ...assigned ? [name] : [] - it may be more readable as ...(assigned ? [name] : [])
    – johansenja
    Jun 1, 2020 at 16:12
  • This seems inefficient... Nov 13, 2022 at 5:47
8

At some point, isn't it easier(or just as easy) to use a forEach

var options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

var reduced = []
options.forEach(function(option) {
  if (option.assigned) {
     var someNewValue = { name: option.name, newProperty: 'Foo' }
     reduced.push(someNewValue);
  }
});

document.getElementById('output').innerHTML = JSON.stringify(reduced);
<h1>Only assigned options</h1>
<pre id="output"> </pre>

However it would be nice if there was a malter() or fap() function that combines the map and filter functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.

3
  • 6
    You might want to check your memes... ;-)
    – Arel
    Mar 26, 2019 at 13:50
  • 3
    But then you wouldn't get to show off your 1 line of 133t JS that no one but you understands. Sep 13, 2020 at 16:11
  • 2
    those names are golden, you should file a proposal to TC39 Oct 20, 2021 at 13:10
7

Use Array.prototype.filter:

function renderOptions(options) {
    return options.filter(function(option){
        return !option.assigned;
    }).map(function (option) {
        return (someNewObject);
    });   
}
1
  • 2
    This doesn't work very well if the value you want is computed in the course of doing the filter; you have to duplicate that part of the code.
    – Lucretiel
    Feb 2, 2022 at 20:12
6

I optimized the answers with the following points:

  1. Rewriting if (cond) { stmt; } as cond && stmt;
  2. Use ES6 Arrow Functions

I'll present two solutions, one using forEach, the other using reduce:

Solution 1: Using forEach

The solution works by using forEach to iterate through every element. Then, in the body of the forEach loop, we have the conditional to act as a filter and it determines whether we are going to append something to the result array.

const options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];
const reduced = [ ];
options.forEach(o => {
  o.assigned && reduced.push( { name: o.name, newProperty: 'Foo' } );
} );
console.log(reduced);

Solution 2: Using reduce

This solution uses Array.prototype.reduce instead of forEach to iterate through the array. It recognizes the fact that reduce has both an initializer and a looping mechanism built in. Other than that, this solution is more or less the same as the forEach solution, so, the difference comes down to cosmetic syntax sugar.

const options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];
const reduced = options.reduce((a, o) => {
  o.assigned && a.push( { name: o.name, newProperty: 'Foo' } );
  return a;
}, [ ] );
console.log(reduced);

I leave it up to you to decide which solution to go for.

1
  • 1
    Why on earth would you use cond && stmt;? This is much more difficult to read and offers no benefits at all.
    – jlh
    Feb 13, 2018 at 8:06
4

I've covert these great answers into utility functions and I'd like to share them:

Example: filter only odd numbers and increment it

  • e.g. [1, 2, 3, 4, 5] -filter-> [1, 3, 5] -map-> [2, 4, 6]

Normally you'd do it like this with filter and map

const inputArray = [1, 2, 3, 4, 5];
const filterOddPlusOne = inputArray.filter((item) => item % 2).map((item) => item + 1); // [ 2, 4, 6 ]

Using reduce

const filterMap = <TSource, TTarget>(
  items: TSource[],
  filterFn: (item: TSource) => boolean,
  mapFn: (item: TSource) => TTarget
) =>
  items.reduce((acc, cur): TTarget[] => {
    if (filterFn(cur)) return [...acc, mapFn(cur)];
    return acc;
  }, [] as TTarget[]);

Using flatMap

const filterMap = <TSource, TTarget>(
  items: TSource[],
  filterFn: (item: TSource) => boolean,
  mapFn: (item: TSource) => TTarget
) => items.flatMap((item) => (filterFn(item) ? [mapFn(item)] : []));

Usage (same for both reduce and flatMap solution):

const inputArray = [1, 2, 3, 4, 5];
const filterOddPlusOne = filterMap(
  inputArray,
  (item) => item % 2, // Filter only odd numbers
  (item) => item + 1 // Increment each number
); // [ 2, 4, 6 ]

JavaScript version

The above codes are in TypeScript but the question asks about JavaScript. So, I've remove all the generics and types for you:

const filterMap = (items, filterFn, mapFn) =>
  items.reduce((acc, cur) => {
    if (filterFn(cur)) return [...acc, mapFn(cur)];
    return acc;
  }, []);
const filterMap = (items, filterFn, mapFn) =>
  items.flatMap((item) => (filterFn(item) ? [mapFn(item)] : []));
3

Using reduce, you can do this in one Array.prototype function. This will fetch all even numbers from an array.

var arr = [1,2,3,4,5,6,7,8];

var brr = arr.reduce((c, n) => {
  if (n % 2 !== 0) {
    return c;
  }
  c.push(n);
  return c;
}, []);

document.getElementById('mypre').innerHTML = brr.toString();
<h1>Get all even numbers</h1>
<pre id="mypre"> </pre>

You can use the same method and generalize it for your objects, like this.

var arr = options.reduce(function(c,n){
  if(somecondition) {return c;}
  c.push(n);
  return c;
}, []);

arr will now contain the filtered objects.

2

Direct use of .reduce can be hard to read, so I'd recommend creating a function that generates the reducer for you:

function mapfilter(mapper) {
  return (acc, val) => {
    const mapped = mapper(val);
    if (mapped !== false)
      acc.push(mapped);
    return acc;
  };
}

Use it like so:

const words = "Map and filter an array #javascript #arrays";
const tags = words.split(' ')
  .reduce(mapfilter(word => word.startsWith('#') && word.slice(1)), []);
console.log(tags);  // ['javascript', 'arrays'];
2

You can use Array.reduce with an arrow function is a single line of code

const options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

const reduced = options.reduce((result, option) => option.assigned ? result.concat({ name: option.name, newProperty: 'Foo' }) : result, []);

document.getElementById('output').innerHTML = JSON.stringify(reduced);
<h1>Only assigned options</h1>
<pre id="output"> </pre>

2

const options = [
  { name: 'One', assigned: true }, 
  { name: 'Two', assigned: false }, 
  { name: 'Three', assigned: true }, 
];

const filtered = options
  .reduce((result, { name, assigned }) => assigned ? result.push(name) && result : result, []);

console.log(filtered);

Perfect, this code complete my entire function and works fine. Just one thing, for the part in assigned ? result.push(name) && result

what it's the purpose for that '&& result' ? :s

thanks

2
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Mar 20 at 16:23
  • Hello and welcome to SO. Please do not post questions as an answer. FYI: The && result usually returns result because result.push(name) returns name, and name happens to be "truish" here. However if name happens to be "falsish" (like in {Name:0, assigned:true } (for somebody called 0 (zero), or '' because the Name is not available) the code fails, because it returns something falsey instead of result! So better replace result.push(name) && result with (result.push(name), result) here. This also has the same number of characters (needs 1 more when minified).
    – Tino
    Aug 16 at 3:44
1

The most efficient way of doing filter + map at once is to process data as a generic iterable, and do both things at once. In this case, you will end up going through data once, at most.

The example below is using iter-ops library, and doing exactly that:

import {pipe, filter, map} from 'iter-ops';

const i = pipe(
    inputArray,
    filter(value => value === 123), // filter on whatever key you want
    map(value => /* any mapping here*/) // remap data as you like
);

// i = iterable that can be processed further;

console.log([...i]); //=> list of new objects

Above, I was saying at most, because if you apply further logic to the iterable result, like limit the number of mapped items, for example, you will end up iterating through your list of objects even less than once:

const i = pipe(
    inputArray,
    filter(value => value === 123), // filter on whatever key you want
    map(value => /* any mapping here*/), // remap as you like
    take(10) // take up to 10 items only
);

Above, we limit iteration further, to stop once 10 resulting items have been generated, and so we are iterating through data less than once. That's as efficient as it gets.

UPDATE

I was asked to add to the answer why this solution is more efficient than reduce, and so here it is...

Array's reduce is a finite operation, which goes through the complete set of data, in order to produce the result. So when you need to do further processing on that output data, you will end up producing a new iteration sequence, and so on.

When you have a complex business logic to be applied to a sequence/iterable, it is always much more efficient to chain that logic, while iterating through the sequence just once. In many cases, you will end up doing complex processing on a sequence, without going through the complete set of data even once. That's the efficiency of iterable data processing.

P.S. I'm the author of the aforesaid library.

0
0

Hey I've just worked on this project and wanted to share my solution based on Array.prototype.flatMap() in MDN docs:

const places=[{latitude:40,longitude:1},{latitude:41,longitude:2},{latitude:44,longitude:2},{latitude:NaN,longitude:NaN},{latitude:45,longitude:4},{latitude:48,longitude:3},{latitude:44,longitude:5},{latitude:39,longitude:13},{latitude:40,longitude:8},{latitude:38,longitude:4}];

let items = places?.map((place) => [{
  latitude: (place.latitude),

  longitude: (place.longitude),
}, ]);

console.log("Items: ", items);

//Remove elements with NaN latitude and longitude

let newItems = places?.flatMap((o) =>
  Number(o.longitude, o.latitude) ?
  {
    lng: Number(o.longitude),
    lat: Number(o.latitude)
  } :
  []
);

console.log("Coordinates after NaN values removed: ", newItems);

0

Same approach as the top answers, using Array.prototype.reduce(), but with updated ES6 syntax, and TypeScript typings, as a generic utility function:

function filterThenMap<T>(l: T[], predicate: (el: T) => boolean, transform: (el: T) => T) {
  return l.reduce((res: T[], el) => {
    if (predicate(el)) {
      res.push(transform(el));
    }
    return res;
  }, []);
}
0

Sigh. Many nice ideas, but nothing fits to what I need.

What I need is:

  • A single function for both, map and filter
  • filtering is done according to the returned value
  • Being able to map all possible values, even true, false, void 0 (aka: undefined) etc.
  • I want to be able to use iterables, not just something like an Array which accidentally happens to have a .length attribute
  • such that I can stop the iteration early

Here is a solution (ES13/ES2022) for this:

'use strict';

function* mapFilter(iter, cb, thisarg)
{
  let stop;
  const guard = _ => (stop=1) && _;
  for (const _ of iter)
    {
      const v = cb.call(thisarg, _, guard);
      if (v !== guard)
        yield v;
      if (stop) break;
    }
}

async function* asyncMapFilter(iter, cb, thisarg)
{
  let stop;
  const guard = _ => (stop=1) && _;
  for await (const _ of iter)
    {
      const v = await cb.call(thisarg, _, guard);
      if (v !== guard)
        yield v;
      if (stop) break;
    }
}

const agents = [
  { name: 'Emma',    assigned: false },
  { name: 'Felix',   assigned: true, assignment:"Mr. Big" },
  { name: 'Harry',   assigned: false },
  { name: 'James',   assigned: true, assignment:"Blofeld" },
  { name: 'Phil',    assigned: false },
  { name: 'Tony',    assigned: false },
  { name: 'Maxwell', assigned: false },
];

const afm = (...a) => Array.from(mapFilter(...a));
const mkiter = function*(...a) { for (const _ of a) yield* _; }

const inAction = () => afm(agents, (agent,_) => agent.assigned ? agent.name : _);
const freeAgents = () => afm(agents, (agent,_) => agent.assigned ? _ : agent.name);
const assignOne = villain => afm(agents, (agent,_) =>
  agent.assigned ? _ : _(agent, agent.assigned = true, agent.assignment = villain)
  )[0];
const assignMany = villains =>
  {
    const iter = mkiter(villains);
    let villain = iter.next();
    return afm(agents, (agent,_) => villain.done ? _(_) :
      agent.assigned ? _ : (agent.assigned = true, agent.assignment = villain.value, villain=iter.next(), agent)
      );
  }

console.log({inActionBefore:inAction(),freeAgentsBefore:freeAgents()});
console.log({newAssigned:assignOne('DeWynter')});
console.log({inActionNow:inAction()});
console.log({moreAssigned:assignMany(['Egan','Thor','Loki'])});
console.log({inActionAfter:inAction(),freeAgentsAfter:freeAgents()});                                                                       

If you are puzzled, the callback function gets two parameters:

  • The current element as the first parameter
  • And as a second parameter a "guard" value (written as _ in the example above) to express ignore and stop
    • If the guard is returned literally, the current element is ignored (filtered)
  • If the guard is called as a function instead, the iteration stops.
  • The (first) argument to the guard (x like in _(x)) is passed out again, so you can use it conveniently in a return statement
    • Hence if you want to stop and ignore the element at the same time, you must write return _(_)
    • as return _() would pass void 0 as the element

This all might look a bit complex, but as you can see, it makes things short and therefor is very readable after you get accustomed to it.

Notes:

  • afm() and mkiter() are only there to improve readability. YMMV

  • If you want to be able to stop early, you need iterators. I did not find a better way than mkiter() to translate anything, which is iterable, into an iterator.

  • assignMany iterates 1 too far in the agents. The code complexity rises a lot (you need to test for villain.done before you call afm() and also test it again after assignment), if you want to skip this superfluous iteration. To implement that is left as an exercise to the reader. ;)

Spoiler: Harry

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.