Changing an array into a list using javascript

function convertArrayToList(inputArray) {
  let list = null;

  for (let i = inputArray.length - 1; i >= 0; i--) {
    list = { value: inputArray[i], rest: list };
  }

  return list;
}
let result = convertArrayToList([10, 20]);
console.log(JSON.stringify(result));

The output I am currently getting is:

{"value":10,"rest":{"value":20,"rest":{"rest":null}}}

But what I actually want is:

{value: 10, rest: {value: 20, rest: null}}

How can I solve this issue? Specifically, how do I change the last "rest" to null instead of another object?

Answer №1

If you want to correct your code, make sure to assign i = arr.length - 1 as the initial value of i. Remember that arrays are 0-indexed, so the index of the last item is always one less than the length of the array:

function convertArrayToList(arr) {
  let rest = null

  for (let i = arr.length - 1; i >= 0; i--) {
    rest = { value: arr[i], rest };
  }

  return rest;
}

const result = convertArrayToList([10, 20]);
console.log(JSON.stringify(result));

An alternative approach would be using Array.reduceRight() to traverse the list from the end, setting the initial value as null:

const convertArrayToList = arr =>
  arr.reduceRight((rest, value) => ({
    value,
    rest
  }), null)

const result = convertArrayToList([10, 20]);
console.log(JSON.stringify(result));

Answer №2

When dealing with array indexes, it's important to remember that they are 0 based. For example, in the array [10, 20], the index of 10 is 0 and the index of 20 is 1. If you start your loop from arr.length, which is 2 in this case, the first arr[i] will result in undefined, causing the loop to run one extra iteration. To avoid this issue when iterating backwards through an array, always begin at length - 1.

function array_to_list(arr) {
  list = null

  for (i = arr.length - 1; i >= 0; i--) {
    list = { value: arr[i], rest: list };
  }

  return list;
}
x = array_to_list([10, 20]);
console.log(JSON.stringify(x));

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

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

Hosting a WCF service in a virtual directory on a shared hosting environment

In the midst of my work on a next js project, I encountered the need to invoke a wcf service. To rectify an error caused by the secure server hosting the site, necessitating the service also be hosted securely, I resorted to creating a virtual directory ...

The fadeOut() function is not functioning properly as the div keeps reappearing even after attempting to

My navigation bar has a unique feature - the subnav expands to fullscreen on hover, while all other subnavs close. However, I encountered an issue with the close button functionality. When clicked, the subnav fades out but then immediately fades back in. ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Confirmation checkbox that retains original value if canceled

Imagine a scenario where there is a checkbox value. When the checkbox value changes, the user is asked, "Do you want to SHOW this item on the website?" or "Do you want to HIDE this item on the website?" Everything seems to be working fine, except for one ...

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

Using Mootools to call a class function from a bound CSS class may lead to an error stating that it is not a function

Utilizing Mootools 1.3.2 Here is the code snippet: var DNReportAbuse = new Class({ Extends: DNUserDialog, comment_id: null, container: null, initialize: function(classname) { var bindclass = $(document.body).getElements(classname); bindclass. ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

Issues with loading JSON data through JQuery

I am completely new to the process of loading JSON text using JavaScript or JQuery. JSON is a new concept for me as well. Currently, I have PHP providing me with some JSON text containing images stored on my server in the following format: [ [{ ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

Encountering an issue with react-dom that needs to be resolved

After updating my node and npm installations, I encountered an error when trying to run my project. Specifically, I am using "react": "^0.13.3" and "react-dom": "0.14.0-beta3" npm WARN unmet dependency /Users/hilarl/Desktop/client/node_modules/react-do ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

accordions that are supposed to adapt to different screen sizes are

My custom responsive accordions are not functioning as expected. The requirement is to display headings and content for desktop view, but switch to accordions on smaller devices. I have managed to do this, however, when resizing the window, the functionali ...

Error TS2322: The function expecting a type of 'FormEventHandler<HTMLFormElement>' cannot be assigned the type '(data: TicketFullDTO) => Promise<void>'

I am currently working on creating an edit form to modify data from a database based on its ID. Here is my approach: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/TextField" ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...