Search code examples
javascriptarrayslodash

Find duplicate or falsy value in a JS object - Javascript


I have an object where it can contain a duplicate and/or a falsy value. I want to compose an array of objects based on that and add a new boolean property based on the check for case-insensitive values.

This is what I have:

const obj = {
  a: 'A',
  b: 'B',
  c: 'C',
  d: 'c',
  e: 'E',
  f: ''
}

console.log(Object.keys(obj).map(i => {
  return {
    key: i,
    isDuplicateOrFalsy: _.filter(
        Object.values(obj),
        j =>
        _.trimEnd(_.toLower(j)) ===
        _.trimEnd(
          _.toLower(
            obj[i]
          )
        )
      ).length > 1 ||
      !_.every(
        Object.values(obj),
        Boolean
      )
  }
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

Expected Output:

[{
  isDuplicateOrFalsy: false,
  key: "a"
}, {
  isDuplicateOrFalsy: false,
  key: "b"
}, {
  isDuplicateOrFalsy: true,
  key: "c"
}, {
  isDuplicateOrFalsy: true,
  key: "d"
}, {
  isDuplicateOrFalsy: false,
  key: "e"
}, {
  isDuplicateOrFalsy: true,
  key: "f"
}]

Please advice.


Solution

  • You could do something similar to this:

    const obj = { a: 'A', b: 'B', c: 'C', d: 'C', e: 'E', f: '' };
    
    const res = Object.entries(obj)
                .map(([key, val], i, arr) => ({
                    key,
                    isDuplicateOrFalsy: !val ||
                      arr.some(([k, v], j) =>
                        j !== i && v.toLowerCase().trim() === val.toLowerCase().trim()
                      )
                }));
                      
    console.log(res);