0

Given these two arrays:

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"]

I have to write a function that takes the two variables and returns a combined string. The expected output is:

"9 ducks 1 elephants 8 pangolins 16 zebras 5 giraffes 1 penguins 42 llamas"

I created an object that resembles the expected string. I now need to print the properties in that order.

function animalsAmounts(arr1, arr2){
    let object = {};
    arr2.forEach((arr2, i) => object[arr2] = arr1[i]);
    return object
    let result = Object.keys(object).map(function(key) {
        return [Number(key), obj[key]];
    }); return result
}

console.log(animalsAmounts(amounts, animals))

It prints:

{ ducks: 9,
  elephants: 1,
  pangolins: 8,
  zebras: 16,
  giraffes: 5,
  penguins: 1,
  llamas: 42 }

I do not know how to return the expected result as a string. I have tried various ways to log both the amounts and animals, but have managed to only return one or the other.

Yumi Park
  • 41
  • 1
  • 1
  • 4

2 Answers2

3

Array.prototype.join() creates one string from items of an array connecting them with whatever you choose.

animals.map((a, i) => `${amounts[i]} ${a}`).join(" ")

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"]

console.log(animals.map((a, i) => `${amounts[i]} ${a}`).join(" "))
marzelin
  • 10,790
  • 2
  • 30
  • 49
0

You could take a dynamic approach for an arbitrary count of array and map value at the same index together and later join to a single string.

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"],
    result = [amounts, animals]
        .reduce((r, a) => a.map((v, i) => (r[i] ? r[i] + ' ' : '') + v), [])
        .join(' ');

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392