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.
JavaScript
x
9
1
Example:
2
name: "Raul", age: 27,
3
name: "Jose", age: 14,
4
name: "Maria", age: 52,
5
name: "Jesus", age: 17,
6
name: "Neo", age: 2
7
8
[Ra, Ma] -> Those are above 18, and their names go abbreviated
9
Here what i tried to do:
JavaScript
1
28
28
1
const amantesGatos = {
2
name: "Raul", age: 27,
3
name: "Jose", age: 14,
4
name: "Maria", age: 52,
5
name: "Jesus", age: 17,
6
name: "Neo", age: 2
7
};
8
// this needs to be filtered
9
10
const idade = amantesGatos.age
11
//i tried to destructuring this array
12
13
const nomeAbrev = [amantesGatos.map(n=>n[0] + n[1])]
14
//Tried to abbreviated names
15
16
//Filter above 18
17
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 444, 17];
18
19
function above18(num) {
20
for (let i = 18; num < i; i--) {
21
if (num < i) {
22
return false;
23
}
24
}
25
return num;
26
}
27
console.log(array.filter(above18));
28
Advertisement
Answer
If I’m understanding correctly the desired outcome is [Ra, Ma]
?
If so you can .filter.map.
JavaScript
1
10
10
1
const peeps = [
2
{name: "Raul", age: 27,},
3
{name: "Jose", age: 14,},
4
{name: "Maria", age: 52,},
5
{name: "Jesus", age: 17,},
6
{name: "Neo", age: 2}
7
]
8
const ofAgePeeps = peeps.filter(({age}) => age > 18)
9
const shortNames = ofAgePeeps.map(({name}) => name.substring(0,2))
10
You can also chain these…
JavaScript
1
2
1
peeps.filter(({age}) => age > 18).map(({name}) => name.substring(0,2))
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…
JavaScript
1
5
1
const obj = {
2
name: 'Tom', age: 2, name: 'Bob', age: 100
3
}
4
console.log(obj) // {name: 'Bob', age: 100}
5