136k views
2 votes
write a function 'transformfirstandlast' that takes in an array, and returns an object with: 1) the first element of the array as the object's key, and

User Michal S
by
7.2k points

1 Answer

5 votes

Answer:

Stack Overflow

Products

Functions and objects in JavaScript

Asked 5 years, 9 months ago

Modified 2 years, 5 months ago

Viewed 2k times

-2

Write a function 'transformFirstAndLast' that takes in an array, and returns an object with:

The first element of the array as the object's key, and

The last element of the array as that key's value.

Example input:

['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'],

The function's return value (output):

{

Queen: 'Beyonce'

}

Note that the input array may have a varying number of elements. Your code should flexibly accommodate that.

E.g. it should handle input like:

['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey']

Here is the code that I wrote:

function transformFirstAndLast(array) {

var arrayList = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];

var arrayList2 = ['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey']

var myObject = {};

key = arrayList.shift();

value = arrayList.pop();

myObject[key] = value

var myObj2 = {};

key = arrayList2.shift();

value = arrayList2.pop();

myObj2[key] = value;

console.log(myObject);

console.log(myObj2);

}

transformFirstAndLast();

The output is this:

{ Queen: 'Beyonce' }

{ Kevin: 'Spacey' }

=> undefined

I know I am supposed to have a return statement, but I could not use two arrays for two objects within one function. Anyway, I do not know if I am doing it totally wrong or I am pretty close to find the solution, but why am I getting that "undefined" message on the third line on the output screen?

javascriptarraysobject

Share

Follow

edited Aug 1, 2020 at 17:46

Peter Mortensen's user avatar

Peter Mortensen

30.8k2121 gold badges104104 silver badges125125 bronze badges

asked Apr 5, 2017 at 21:41

Beck TJ's user avatar

Beck TJ

111 bronze badge

because your function doesn't return anything (=undefined) and your output comes from the console.log calls inside the function –

xDreamCoding

Apr 5, 2017 at 21:49

Add a comment

3 Answers

Sorted by:

Highest score (default)

3

Just use the array indexes to get the value and create the objects:

function transformFirstAndLast(array) {

var myObject = {};

myObject[array[0]] = array[array.length-1];

return myObject;

}

var arrayList = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];

var arrayList2 = ['Kevin', 'Bacon

User Jasen
by
7.1k points