0

I would like to extend the question that has been asked some time ago: How to get distinct values from an array of objects in JavaScript?

my case is very similar: I have the following:

var array = 
    [
        {"name":"Doctor", "age":17}, 
        {"name":"Doctor", "age":17},
        {"name":"Doctor", "age":18},
        {"name":"Nurse", "age":17}, 
        {"name":"Nurse", "age": 35}
        {"name":"Nurse", "age": 35}
    ]

What is the best way to be able to get an array of all of the distinct ages, but for chosen speciality such that I get an result array of:

filter by doctor parameter: [17, 18]

filter by nurse parameter: [17, 35]

3
  • Maybe .filter then pass that to new Set? Commented Aug 14, 2022 at 10:51
  • do you mean just filter first and then apply something like: array.map(item => item.age) .filter((value, index, self) => self.indexOf(value) === index) Commented Aug 14, 2022 at 10:52
  • I'd like to know what med-school hands out medical degrees to high-school kids... Commented Aug 14, 2022 at 10:53

2 Answers 2

2

Use array functions

const array = [{
    "name": "Doctor",
    "age": 17
  },
  {
    "name": "Doctor",
    "age": 18
  },
  {
    "name": "Nurse",
    "age": 17
  },
  {
    "name": "Nurse",
    "age": 35
  }
]

console.log(getUniqueAges(array, 'Doctor'))
console.log(getUniqueAges(array, 'Nurse'))

function getUniqueAges(data, name) {
  return [...new Set(data
    .filter(datum => datum.name === name)
    .map(datum => datum.age))]
}

Sign up to request clarification or add additional context in comments.

Comments

1

just like in the answer you linked, but you filter (the example below is filtered by name==="doctor) the array before you pass it to the Set:

const data =     [
    {"name":"Doctor", "age":17}, 
    {"name":"Doctor", "age":18},
    {"name":"Nurse", "age":17}, 
    {"name":"Nurse", "age": 35}
];
const unique = [...new Set(data.filter(item => item.name === "doctor").map(item => item.age))]; // [ '17', '18']

1 Comment

your solution works well, but was second, so I can give you only the point up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.