My task involves converting an array that consists of a mix of objects and strings into another object array.
The initial array:
[
{"text": "Address"},
{"text": "NewTag"},
{"text": "Tag"},
"Address",
"Name",
"Profile",
{"text": "Name"},
]
The desired output array:
[
{"Tag": "Address", Count: 2},
{"Tag": "Name", Count: 2},
{"Tag": "NewTag", Count: 1},
{"Tag": "Profile", Count: 1},
{"Tag": "Tag", Count: 1},
]
This is the code I have written to achieve this goal:
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 am curious to know if there exists a more efficient and elegant approach to solving this problem?