JavaScript's Functions and Objects: An Overview

Create a function called 'transformFirstAndLast' which takes an array as input and outputs an object with:

  1. The first element of the array as the key of the object.
  2. The last element of the array as the value of that key.

For example, if the input is:

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

The return value of the function should be:

{
  Queen: 'Beyonce'
}

Your code should be able to handle arrays of varying lengths. For instance:

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

Here is your existing code:

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 you are getting:

{ Queen: 'Beyonce' }
{ Kevin: 'Spacey' }
=> undefined

You mentioned the issue with the "undefined" message - this might be due to missing a return statement in your function. Additionally, it seems like you are using two predefined arrays instead of utilizing the function parameter 'array'. Try modifying your code to properly accept 'array' as a parameter and generate the desired output accordingly.

Answer №1

Utilize the array indexes to retrieve values and build objects:

function extractFirstAndLast(array) {

  var myObject = {};
  myObject[array[0]] = array[array.length-1];
  return myObject;
}

var firstAndLastArray = ['Apple', 'Banana', 'Cherry', 'Date'];
var secondArray = ['Tomato', 'Potato', 'Lettuce', 'Carrot']

console.log(extractFirstAndLast(firstAndLastArray));
console.log(extractFirstAndLast(secondArray));

Answer №2

To easily achieve the desired outcome, simply create an empty object and set the first element of the given array as a key, and the last element as its corresponding value.

var fruitList = ['Apple', 'Banana', 'Cherry', 'Date'],
    veggieList = ['Carrot', 'Broccoli', 'Lettuce', 'Spinach', 'Cabbage'];
 

function assignFirstAndLast(arr) {
  var result = Object.create(null);
      result[arr[0]] = arr[arr.length-1];
      console.log(result);
      return result;
}

assignFirstAndLast(fruitList);
assignFirstAndLast(veggieList);

Answer №3

Why am I receiving the "undefined" message on the output screen's third line?

The displayed output is:

{ Queen: 'Beyonce' }
{ Kevin: 'Spacey' }
=> undefined

This happens because the function, transformFirstAndLast, lacks a return statement. A function must always return something; therefore, it defaults to undefined.

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);        <-- first output
  console.log(myObj2);          <-- second output
}
transformFirstAndLast();        <-- third output

The third output involves calling the function but not returning any value. If you simply had 1;, it would output 1.

To address this issue, you can:

  1. Utilize the comma operator for another action; e.g., transformFirstAndLast(), 'done';
  2. Add a return statement in your function like return true; ideally, you'd want to return the object with return myObject;

Illustration

Here's a comprehensive example of accepting arrays, multiple arrays, or even strings as arguments in the function and returning the created object.

"use strict";

var arrayList = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];
var arrayList2 = ['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey'];

console.log(
  'Example 1 (passing arrays):\n',
  transformFirstAndLast(arrayList, arrayList2)
);
console.log(
  'Example 2 (passing strings):\n',
  transformFirstAndLast('thank','you','mother')
);


function transformFirstAndLast() {
  var obj = {}, arrs = [];
   
  if (!Array.isArray(arguments[0]))
    // handle a bunch of strings (Example 2)
    arrs = [Object.keys(arguments).map(k=>arguments[k])];
  else
    // handle 1 or more array
    arrs = [...arguments];
  
  arrs.forEach( arr => {
    obj[arr[0]] = arr[arr.length-1];
  });
  
  return obj;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I incorporate a JavaScript module into my Typescript code when importing from Typeings?

Exploring Angular2 and Typescript with the help of mgechev's angular2-seed for a new project has been an interesting experience. However, I have encountered a problem along the way. My intention is to incorporate Numeral into a component, and here ar ...

Angular.js model that is updated by checkboxes

In my project, I have created a model that is linked to several other models. For instance, let's consider a scenario similar to a Stack Overflow question associated with tags. Before making a POST or PUT request, the final Object may appear like this ...

When using Laravel with jQuery Ajax, the search for the file address is unsuccessful

Learning Laravel has been a challenging journey for me. I've encountered numerous problems that have made it feel like more of a hindrance than a helpful tool. But the real story lies elsewhere. Working with Laravel 4 and jQuery 2, I attempted to fet ...

Executing an AngularJS function through CasperJS is a common task that can

I am facing a challenge with testing a directive within a controller. The unit tests I am trying to write involve executing this code, which is triggered not by a click event but rather by a socket.io emit. Instead of attempting to mock socket.io, I am exp ...

What prompted the modification of this statement from C99 to C11?

Understanding the C99 Standard: The C99 Standard states that an object can only have its stored value modified once between two sequence points during the evaluation of an expression. Differences with the C11 Standard: In the C11 Standard, it is cla ...

Utilize form binding with Vue router's push method

I am currently developing a filtering component for a grid system. This component includes various fields where user inputs are stored in a model. When the user fills out the form and submits it, I have the following code for the submission process: method ...

Guide to automatically inserting text into an html form and submitting it without manual intervention

Currently, I am in the process of a project where my main goal is to design an HTML form for submitting replies. One interesting feature I want to include is an option for users who are feeling lazy to simply click on "auto-generate comment", which will ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

Issue with pop up window causing button click event to malfunction

I am facing an issue where the button click event works fine outside of a pop-up window but does not fire when inside the pop-up window. In my HTML code, the part that calls the button event outside of the pop-up window works perfectly, but inside the pop- ...

I encountered a RangeError with code [ERR_HTTP_INVALID_STATUS_CODE] due to an invalid status code being undefined

I have encountered a specific error while running my note-taking app. The error seems to be related to the following piece of code - app.use((err,req,res,next)=>{ res.status(err.status).json({ error : { message : err.message ...

Using JavaScript within WordPress to achieve a seamless scrolling effect

I am seeking to implement a Smooth Scroll effect on my website located at . The site is built on WordPress and I am facing difficulty in connecting JavaScript/jQuery in WordPress. I have come across various WordPress plugins, but they either do not meet my ...

The function FormatCurrency is non-existent

I need assistance with converting a textbox value into a currency using the jquery.formatCurrency-1.4.0.js plugin. My JavaScript function is set up like this: $(document).ready(function() { $('.currency').blur(function() { $(&apo ...

Turning a JSON dot string into an object reference in JavaScript: A simple guide

Having a JSON object labeled test with values like this: {"items":[{"name":"test"}]}, I need a way to apply the string items[0].name to it in order to search for a specific value (test.items[0].name). Currently, my only idea is to create a function that pa ...

Choose an element that has been generated dynamically using jQuery

Here is an example HTML table to work with: <table id="#myTable"> <tr id="#row123"><td>Content</td></tr> </table> To insert a new row using jQuery, you can use the following code: $('#myTable').prepend(&ap ...

Design a unique UIButton that can be customized to display various data points

I am facing a challenge with displaying an array of content. The issue is that creating a button for each item in the array is not practical, especially if the array has many items. I am seeking help to come up with a solution to generate a single button t ...

Step-by-step guide on how to effectively send a NodeJS request and stream it into a separate response

Currently, I am in the process of developing an API to interact with a specific map service that requires the use of an API key. It is crucial for me to keep this API key private. To achieve this, I plan to make internal calls within my server's own A ...

Issues with displaying data in Angular ChartJS are troubling users

Currently utilizing Angular 6, my goal is to incorporate a Chart.js line chart. Essentially, I am fetching two arrays from my API: one named weight_data and the other named weight_date, which I then utilize for the chart. After receiving the arrays from t ...

Implementing template loading on page load with state in AngularJS

When my application loads, I want the nested view list-patents.htm to be displayed. The main navigation is on my index.htm, featuring two nav items: transactions and patents. If you click on patents, two sub-menu items will appear: list patents and add p ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Update a separate React component in response to the interaction with a different React component

Currently, I am working with a react component named Interest Category that showcases an initial set of Interest categories. Another react component called CreateInterestCategoryDialog, which functions as a modal, is responsible for creating a new entity I ...