0

I have an array of objects being returned to me as data, I'm looking to Create a new set of data, while retaining the old one for future use.

I'm trying to loop through the data given to create a new set of data that only contains age, but also removes any duplicates. I'm not too sure where to start with this.

data = [
    {
        "firstName": "John",
        "lastName": "Doe",
        "age": "99"
    }, 
    {
        "firstName": "Jimmy",
        "lastName": "Hendricks",
        "age": "50"
    }, 
    {
        "firstName": "William",
        "lastName": "Shakespeare",
        "age": "22"
    }, 
    {
        "firstName": "Jane",
        "lastName": "Eyre",
        "age": "50"
    }
]

What I'd like to end up with is something like this:

newData = [
        {"age": "99"}, 
        {"age": "50"}, 
        {"age": "22"}
]
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Nick
  • 2,261
  • 5
  • 33
  • 65

4 Answers4

2

Or you can just use Set for eliminating duplicates:

// ages variable contain just the ages
const ages = data.map(person => person.age);
// new Set(ages) will remove duplicated values:
const newSet = Array.from(new Set(ages)).map(age => ({ age: age }));
Oriol Grau
  • 609
  • 6
  • 8
2

Wow, so many approaches! Here is another one, purely functional:

data = [ { "firstName": "John", "lastName": "Doe", "age": "99" }, { "firstName": "Jimmy", "lastName": "Hendricks", "age": "50" }, { "firstName": "William", "lastName": "Shakespeare", "age": "22" }, { "firstName": "Jane", "lastName": "Eyre", "age": "50" } ]; 

console.log(
 Object.keys(data.reduce((obj,o)=>
      (obj[o.age]=1,obj),{}))
.map(k=>({age:k}))
)
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
1
let newData = [];
let uniques = [];
data.forEach(el => {
    if(!uniques.includes(el.age)){
      newData.push({age: el.age});
      uniques.push(el.age);
}
});
Nad
  • 516
  • 5
  • 18
1

You can use .map and .filter combined with a Set for this:

const data = [
    {
        "firstName": "John",
        "lastName": "Doe",
        "age": "99"
    }, 
    {
        "firstName": "Jimmy",
        "lastName": "Hendricks",
        "age": "50"
    }, 
    {
        "firstName": "William",
        "lastName": "Shakespeare",
        "age": "22"
    }, 
    {
        "firstName": "Jane",
        "lastName": "Eyre",
        "age": "50"
    }
]

const newdata = data
  .map(({age}) => ({age})) // convert `{age: <value of age>}`
  .filter(function({age}) {
    const isUnique = !this.has(age); //check if already present
    this.add(age); //add anyway

    return isUnique; //filter keeping uniques
  }, new Set());//use a Set as the `this` context for the filter
  
console.log(newdata);
VLAZ
  • 26,331
  • 9
  • 49
  • 67