Search code examples
javascriptarraysobjectkeyfor-in-loop

First value of an array as a Key name and last one as a value JavaScript?


I am a beginner programming student and I have some doubts about how to focus and understand this exercise.

Anyone could explain me the logical to face this exercise?

I have an array like this: ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'] and I want this result: { Queen : 'Beyonce' }

I want to make function to return the following:

  1. the first element of the array as the object's key
  2. the last element of the array as that key's value. I am doing a var key in array and then a loop through the array

Someone recommended me to do it as follows, but I don´t understand very well how shift and pop works here, because shift delete the first value of the array and pop the last one.

Anyone could help me?

function transformFirstAndLast(array) {
  // your code here
  let myobj={}
  myobj[array.shift()] = array.pop();
  
  console.log(myobj);
}


var output = transformFirstAndLast(['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']);
console.log(output);


Solution

  • In short, these methods, mutate the original array (removing the first or last element) but also return the element that was removed.

    arr.shift(): explained:

    (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)

    const myArr = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];
    
    //remove the first element and save it in the variable firstElem
    const firstElem = myArr.shift();
    
    console.log(firstElem); //output: "Queen"
    console.log(myArr); //output: "['Elizabeth', 'Of Hearts', 'Beyonce']"

    arr.pop(): explained:

    (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)

    const myArr = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];
    
    //remove the last element and save it in the variable firstElem
    const lastElem = myArr.pop();
    
    console.log(lastElem); //output: "Beyonce"
    console.log(myArr); //output: "['Queen', 'Elizabeth', 'Of Hearts']"

    So, in order to make it clear for your example see this slightly modified code:

    function transformFirstAndLast(array) {
      // your code here
      let myobj={}
      const firstElem = array.shift();
      const lastElem = array.pop();
      myobj[firstElem] = lastElem
      
      //console.log(myobj);
      return myobj;
    }
    
    
    var output = transformFirstAndLast(['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']);
    console.log(output);