'Setting a unique set of keys into a new array

I have a array of objects:

let data = [{ "Borough": "Bronx", "Neghborhood": "Baychester" }, { "Borough": "Bronx", "Neghborhood": "Bedford Park" }, { "Borough": "Queens", "Neghborhood": "Astoria" }, { "Borough": "Queens", "Neghborhood": "Auburndale" }, { "Borough": "Manhattan", "Neghborhood": "Midtown East" }, { "Borough": "Manhattan", "Neghborhood": "Midtown South" }, { "Borough": "Manhattan", "Neghborhood": "Midtown West" }, { "Borough": "Brooklyn", "Neghborhood": "Prospect Park" }, { "Borough": "Brooklyn", "Neghborhood": "Prospect Park South" }, { "Borough": "Brooklyn", "Neghborhood": "Red Hook" }];

I want to iterate over it and create a new array that wil hold the unique keys , let newArr = ["Bronx, "Brooklyn", "Manhattan", "Queens"].

What i tried is:

    const getUniqueValues = data.map((elm, i) => {
       
        let newArr  = [];
        if (!newArr.includes(elm['Borough'])) {
            newArr.push(elm.Borough)
        }
       
        return newArr;
       
     }
    )

but it gives me back just an array of elements with each element inside an array of its own, so i understand that that's what map does, however i don't understand why the duplicates remain. Also, i'm sure that i'm over computing it so i would love suggestions on the most simple code. Cheers!



Solution 1:[1]

Try to use the reduce function:

let data = [{ "Borough": "Bronx", "Neghborhood": "Baychester" }, { "Borough": "Bronx", "Neghborhood": "Bedford Park" }, { "Borough": "Queens", "Neghborhood": "Astoria" }, { "Borough": "Queens", "Neghborhood": "Auburndale" }, { "Borough": "Manhattan", "Neghborhood": "Midtown East" }, { "Borough": "Manhattan", "Neghborhood": "Midtown South" }, { "Borough": "Manhattan", "Neghborhood": "Midtown West" }, { "Borough": "Brooklyn", "Neghborhood": "Prospect Park" }, { "Borough": "Brooklyn", "Neghborhood": "Prospect Park South" }, { "Borough": "Brooklyn", "Neghborhood": "Red Hook" }];

const reduced = data.reduce((carry, current) => {
  if(!carry.some(e => e.Borough == current.Borough)){
    carry.push(current);
  }
  return carry;
}, []);

console.log(reduced)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Vidaurre Arroyo