Skip to content
Advertisement

Map + filter – Showing people that have < 18 years and abbreviate names

I wanted to be able to transform the age into a single array, so I would already know how to filter, then apply the mapping to only show people over 18 years old, in addition, to present the abbreviated names of the people.

Example:
 name: "Raul", age: 27,
 name: "Jose", age: 14,
 name: "Maria", age: 52,
 name: "Jesus", age: 17,
 name: "Neo", age: 2

[Ra, Ma] -> Those are above 18, and their names go abbreviated

Here what i tried to do:

const amantesGatos = {  
name: "Raul", age: 27,
name: "Jose", age: 14,
name: "Maria", age: 52,
name: "Jesus", age: 17,
name: "Neo", age: 2
};
// this needs to be filtered

const idade = amantesGatos.age
//i tried to destructuring this array

const nomeAbrev = [amantesGatos.map(n=>n[0] + n[1])]
//Tried to abbreviated names

//Filter above 18
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 444, 17];

function above18(num) {
    for (let i = 18; num < i; i--) {
        if (num < i) {
            return false;
        }
    }
    return num;
}
console.log(array.filter(above18));

Advertisement

Answer

If I’m understanding correctly the desired outcome is [Ra, Ma]?

If so you can .filter.map.

const peeps = [
  {name: "Raul", age: 27,},
  {name: "Jose", age: 14,},
  {name: "Maria", age: 52,},
  {name: "Jesus", age: 17,},
  {name: "Neo", age: 2}
]
const ofAgePeeps = peeps.filter(({age}) => age > 18)
const shortNames = ofAgePeeps.map(({name}) => name.substring(0,2))

You can also chain these…

peeps.filter(({age}) => age > 18).map(({name}) => name.substring(0,2))

That said your amantesGatos is an object with a bunch of duplicate keys and not an array. Which means it’s really an object with only the last name and age. For example…

const obj = {
  name: 'Tom', age: 2, name: 'Bob', age: 100 
}
console.log(obj) // {name: 'Bob', age: 100}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement