Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash transform array mix of objects and strings

I have an array that contains a mix of objects and strings. I need to transform the array into another object array.

The input array:

[
  {"text": "Address"},
  {"text": "NewTag"},
  {"text": "Tag"},
  "Address",
  "Name",
  "Profile",
  {"text": "Name"},
]

The out array should like this:

[
  {"Tag": "Address", Count: 2},
  {"Tag": "Name", Count: 2},
  {"Tag": "NewTag", Count: 1},
  {"Tag": "Profile", Count: 1},
  {"Tag": "Tag", Count: 1},
]

Here is my code (it looks stupid):

var tags = [], tansformedTags=[];   
for (var i = 0; i < input.length; i++) {
  if (_.isObject(input[i])) {
    tags.push(input[i]['text']);
  } else {
    tags.push(input[i]);
  }
}
tags = _.countBy(tags, _.identity);
for (var property in tags) {
  if (!tags.hasOwnProperty(property)) {
    continue;
  }
  tansformedTags.push({ "Tag": property, "Count": tags[property] });
}
return _.sortByOrder(tansformedTags, 'Tag');

I want to know if there is a better and more elegant way to perform this operation?

like image 610
YuMei Avatar asked May 31 '26 00:05

YuMei


1 Answers

By using map() and countBy():

_(arr)
    .map(function(item) {
        return _.get(item, 'text', item);
    })
    .countBy()
    .map(function(value, key) {
        return { Text: key, Count: value };
    })
    .value();
like image 98
Adam Boduch Avatar answered Jun 01 '26 13:06

Adam Boduch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!