I have a list of String with duplicate entries , So i want to remove them irrespective of Case
let duplicates = ['Hello', 'Hi', 'hello'];
let uniques = _.methodName(duplicates);
// output should be
['hello','Hi'] OR ['Hello','Hi']
I have a list of String with duplicate entries , So i want to remove them irrespective of Case
let duplicates = ['Hello', 'Hi', 'hello'];
let uniques = _.methodName(duplicates);
// output should be
['hello','Hi'] OR ['Hello','Hi']
One solution that avoids the need for a dependancy like lodash would be the following "vanilla js" approach:
let duplicates = ['Hello', 'Hi', 'hello'];
/* Pluck the values of the object mapping to an array */
let uniques = Object.values(
/* "Reduce" input array to an object mapping */
duplicates.reduce((obj, str) =>
/* Insert str value into obj mapping with lower case key */
({ ...obj, [str.toLowerCase()] : str }), {})
);
console.log(uniques)
Here an object mapping case insenstive keys to case sensitive values is built via Array#reduce
. This mapping ensures that unique values are obtained irrespective of case. The Object#values
method is then used to transform that mapping to the required uniques
array.
If Object#values
is not available in your browser, you can use the following solution:
let duplicates = ['Hello', 'Hi', 'hello'];
let mapping = duplicates.reduce((obj, str) =>
({ ...obj, [str.toLowerCase()] : str }), {})
let uniques = Object.keys(mapping).map(k => mapping[k])
console.log(uniques)
Hope that helps!
You can use _.uniqWith()
with a callback as following:
let duplicates = ['Hello', 'Hi', 'hello'];
let uniques = _.uniqWith(duplicates, (a,b) => a.toLowerCase() === b.toLowerCase())
console.log(uniques);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
It's very simple with _.uniq
and _.map
Here is an exmaple:
let uniqueData = _.uniq(_.map(duplicates, (d) => d.toLowerCase()));
You can use _.uniqBy()
with _.toLower()
as iteratee:
const duplicates = ['Hello', 'Hi', 'hello'];
const result = _.uniqBy(duplicates, _.toLower);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>