Helmut Granda Helmut Granda - 3 months ago 7
Javascript Question

Alter result for map in underscore.js

Since map will return "undefined" for elements not matched what is the best way to return only those that match?



let items: string[] = ["false", "false", "true"];

let newItems: string[] = _.map(items, function(item) {
if (item === "true") {
return "newItem";
}
});

console.log(newItems);
// newItems = [undefined,undefined,"newItem"];

let filterItems: string[] = _.filter(items, function(item) {
if (item === "true") {
return "newItem";
}
});

console.log(filterItems);
// filterItems = ["true"]

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>





I could use _.filter however filter would return the value of "true" instead "newItem" as I need it.

Any recommendations?

Answer

You could use reduce to do both operations at the same time:

let items: string[] = ["false", "false", "true"];

let newItems: string[] = _.reduce(items, function(memo, item) {
  if (item === "true") {
    memo.push("newItem");
  }
  return memo;
}, []);

let items = ["false", "false", "true"];

let newItems = _.reduce(items, function(memo, item) {
  if (item === "true") {
    memo.push("newItem");
  }
  return memo;
}, []);

console.log(newItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Comments