Karl Bateman Karl Bateman - 6 months ago 13
Javascript Question

Lodash finding a partial uniqueness within array values

The following code, returns an array of unique value from the

data
array. However, what I am trying to achieve is return true if there is a uniqueness found at
value1:value2
. As you can see from the code below
value1:value2:value3
and
value1:value2:value4
match this criteria. A lodash technique to produce this functionality would be ideal, however for the sake of understanding a solution I would gladly welcome plain 'ol' javascript.

NOTE jQuery and HTML have been included to illustrate my question. The javascript I am after, would be running on NodeJS.

UPDATE

Expected output from running the code below would
true
as there is a match between
value1:value2:value3
and
value1:value2:value4
i.e.
value1:value2
exist in both values.

UPDATE

Please see the following fiddle for an example of the output I am after.

UPDATE

Included is an example of the output I am after. This is the desired functionality, however I would like a lodash way of achieving the same result.



$(document).ready(function() {
var data = [
'value1:value2:value3',
'value1:value2:value4',
'value5:value6:value7',
'value1:value2:value3'
];
var partialValueMatch = function(data) {
var lookup = _.uniqBy(data, function(str){
return str.substring(0, str.lastIndexOf(':'))
});
if(lookup.length < data.length) return true;
return false;
}
var $output = $('#output');
$output.html(partialValueMatch(data));
});

#output {
background: #fafafa;
border: 1px solid #d8d8d8;
padding: 5px 10px;
font-family: monospace;
border-radius: 2px;
color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
<div id="output"></div>




Answer

You can use _.uniqBy

 var data = [
    'value1:value2:value3',
    'value1:value2:value4',
    'value5:value6:value7',
    'value1:value2:value3'
    ];

var output = _.uniqBy(data,function(str){
   return str.substring(0,str.lastIndexOf(':'))
 });
console.log(output);
console.log('Is duplicates found:',output.length<data.length);

This will give you uniq data as below

//["value1:value2:value3", "value5:value6:value7"]
//Is duplicates found: true