简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM