Nick
Nick

Reputation: 2549

ES6 - Create new object from existing data, using only one property, and removing any duplicates?

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"}
]

Upvotes: 0

Views: 77

Answers (4)

Carsten Massmann
Carsten Massmann

Reputation: 28196

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}))
)

Upvotes: 2

VLAZ
VLAZ

Reputation: 29039

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);

Upvotes: 1

Oriol Grau
Oriol Grau

Reputation: 629

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 }));

Upvotes: 2

Nad
Nad

Reputation: 556

let newData = [];
let uniques = [];
data.forEach(el => {
    if(!uniques.includes(el.age)){
      newData.push({age: el.age});
      uniques.push(el.age);
}
});

Upvotes: 1

Related Questions