2

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.

2 Answers 2

8

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
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I was looking for. gonna have a nicer weekend now, thanks!
0

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>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.