DonJuwe
DonJuwe

Reputation: 4563

How to check if string within object is unique in array

I have an array of strings:

var arr = [
    {str: 'abc'},
    {str: 'def'},
    {str: 'abc'},
    {str: 'ghi'},
    {str: 'abc'},
    {str: 'def'},
];

I am searching for a smart way to add a boolean attribute unique to the objects whether str is unique:

var arr = [
    {str: 'abc', unique: false},
    {str: 'def', unique: false},
    {str: 'abc', unique: false},
    {str: 'ghi', unique: true},
    {str: 'abc', unique: false},
    {str: 'def', unique: false},
];

My solution contains three _.each() loops and it looks terrible... Solutions with lodash preferred.

Upvotes: 2

Views: 738

Answers (2)

hampusohlsson
hampusohlsson

Reputation: 10219

You don't need any libraries, vanilla js works:

var map = [];
var arr = [
    {str: 'abc'},
    {str: 'def'},
    {str: 'abc'},
    {str: 'ghi'},
    {str: 'abc'},
    {str: 'def'},
];
  
arr.forEach(function(obj) {
    if (map.indexOf(obj.str) < 0) {
      map.push(obj.str);
      obj.unique = true;
      return;
    }
    arr.forEach(function(o) {
      if (o.str === obj.str) o.unique = false;
    });
});

document.write("<pre>");  
document.write(JSON.stringify(arr, null, "  "));
document.write("</pre>");

Upvotes: 0

Magus
Magus

Reputation: 15104

You can use where to filter an object. Then you can know if your string is unique in the object.

_.each(arr, function(value, key) {
    arr[key] = {
        str : value.str,
        unique : _.where(arr, { str : value.str }).length == 1 ? true : false
    };
});

Maybe better version with a map :

arr = _.map(arr, function(value) {
    return {
        str : value.str,
        unique : _.where(arr, { str : value.str }).length == 1 ? true : false
    };
});

Upvotes: 8

Related Questions