aguadamuz
aguadamuz

Reputation: 421

Javascript: return the first value from arrays within an object

I am working on a javascript homework problem and am a bit stuck:

Create a function called getFirstAnimals that returns an array of all the first animals in the object. Example: [‘bears’,’penguins’,panther’,’flea’]

I scripted the following function:

var animals = { 
mammals:['bears','lions','whales','otters'], 
birds:['penguins','ducks','swans','chickens'], 
cats:['panther','mountain lion','leopard','snow tiger'], 
insects: ['flea','mosquito','beetle','fly','grasshopper']
}

function getFirstAnimals(array) {
    var firstAnimals = [];
    for (key in array) {
        firstAnimals.push(array[key].slice(0,1))
    }
    return firstAnimals;
}

console.log(getFirstAnimals(animals));

my problem is that the output I am generating is an array of arrays made up of the first animals, [Array[1], Array[1], Array[1], Array[1]], and not the strings, [‘bears’,’penguins’,panther’,’flea’]. Any suggestions on how to get the desired output is much appreciated.

Upvotes: 0

Views: 263

Answers (4)

Michelangelo
Michelangelo

Reputation: 5948

A oneliner: console.log(animals[Object.keys(animals)[0]]);

Upvotes: 0

Tolgahan Albayrak
Tolgahan Albayrak

Reputation: 3206

Yet another approach

var animals = { 
mammals:['bears','lions','whales','otters'], 
birds:['penguins','ducks','swans','chickens'], 
cats:['panther','mountain lion','leopard','snow tiger'], 
insects: ['flea','mosquito','beetle','fly','grasshopper']
}

function getFirstAnimals(array) {
  return Object.keys(array).map(v => array[v][0]);
}

console.log(getFirstAnimals(animals));

Upvotes: 0

Janar
Janar

Reputation: 2701

You can use

firstAnimals.push(array[key][0])

for that. It gets the first element from the array

Upvotes: 1

alexoakley1
alexoakley1

Reputation: 565

Instead of pushing array[key].slice(0,1) you need to push array[key][0], where [0] is getting you the first item in the array.

Upvotes: 1

Related Questions