Search code examples
javascriptlodash

How to traverse an Array of Objects with multiple elements to make a new array with only the duplicates using Lodash


So, here's my situation:

I have an array of objects, there are 3300+ of them and it could be less or more.

I'm getting it just fine and now, I want to take and SCAN that array of objects, and find all the DUPLICATE markets and make a NEW array with just 1 of the many elements in that array of objects.

Here's an dumbed down example of the many objects:

[{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "IL",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
},{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "CA",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
},{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "ATLANTA GA",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
},{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "ATLANTA GA",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
},{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "REGION 5",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
},{
  "EL1": "",
  "EL2": "ASDGFDSFFE 1:15",
  "MARKET": "REGION 5",
  "EL3": "CHCHILJH",
  "EL4": "A:B::1243",
  "EL5": "ADFD"
}]

What I want is a new array that just returns in Alphabetical Order:

["ATLANTA GA", "CA", "IL", "REGION 5"]

Here's my code thus far:

        $scope.nestAssociation = (arr) => {

            let newArr = JSON.parse(arr);

            // console.log("incoming array: ", newArr);

            const uniqueMarketNames = $scope._.uniqBy(newArr.message, 'MARKET'); // removed if had duplicate id
            // TRIED THIS...  
            // const uniqueMarkets = _.uniqWith(
            //  newArr.message,
            //  (MarketsAll) =>
            //    MarketsAll === newArr.message.MARKET
            // );
            
            let uniqueMarkets = $scope._.uniqBy(newArr, function(elem) {
                return JSON.stringify(_.pick(elem, ['a', 'b']));
            });

            console.log("Unique Market names: ", uniqueMarketNames);
            console.log("Unique Markets: ", uniqueMarkets);

            return uniqueMarkets;
        }

What I got is the ENTIRE BLOCK of objects along with 12 of the duplicates out of 3300+ objects.

So, it's working but not, giving me JUST the MARKET


Solution

  • This was what worked for me.

            $scope.nestAssociation = (arr) => {
    
                let newArr = JSON.parse(arr);
    
                const uniqueMarketNames = $scope._.uniqBy(newArr.message, 'MARKET'); // removed if had duplicate id
    
                let newMarketArray = [];
                for(var i = 0; i < uniqueMarketNames.length; i++) {
                    newMarketArray.push(uniqueMarketNames[i].MARKET);
                }
    
                console.log("MARKETS: ", newMarketArray);
    
                return newMarketArray;
            }