Lodash: Extract property, split array, get unique values

3.9k views Asked by At

In my JS project, I am using Lodash library to Extract property, split array, get unique values.

  var taskobj = [
      {'taskno':'a', 'team':'1,2'},
      {'taskno':'b', 'team':'3,4'},
      {'taskno':'c', 'team':'2,4'},
    ];

 //Looping through the object to convert string to array
  _.forEach(taskobj, function(value, key) {
    taskobj[key].team = _.split(taskobj[key].team,',');
  });

// using _.map to extract team and return array
// using _.flatten to flatten array
// using _.uniq to get unique values from flattned array.

return _.uniq(_.flatten(_.map(taskobj,'team')));
// logs - [1,2,3,4]

Is this the most efficient way to achieve this?

3

There are 3 answers

4
ryeballar On BEST ANSWER

This can be achieved by using lodash#flatMap with an iteratee that splits the team string into an array, which is then flattened by the mentioned function and then use lodash#uniq to get the final result.

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

var taskobj = [
    {'taskno':'a', 'team':'1,2'},
    {'taskno':'b', 'team':'3,4'},
    {'taskno':'c', 'team':'2,4'},
];

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

0
Piyush Patel On

Use simpler version

try this

var teams = [];
var taskobj = [
      {'taskno':'a', 'team':'1,2'},
      {'taskno':'b', 'team':'3,4'},
      {'taskno':'c', 'team':'2,4'},
    ];

taskobj.map(obj => {
  var teamSplit = obj.team.split(',');
  teams = [...teams, ...teamSplit];
})

var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)

JsBin link http://jsbin.com/bedawatira/edit?js,console

0
Taki On

you can use reduce and start with a new Set() and add the values of team every time ( then convert it back to an array with the spread operator )

var taskobj = [
  {'taskno':'a', 'team':'1,2'},
  {'taskno':'b', 'team':'3,4'},
  {'taskno':'c', 'team':'2,4'},
];

var result = [...taskobj.reduce((acc, {team}) => {
  team.split(',').forEach(e => acc.add(e))
  return acc
}, new Set())]

console.log(result)