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

Steps for obtaining images using lazy loading: <img loading="lazy"

After successfully utilizing the JavaScript-executer to locate the ImageElement, I encountered an error when attempting to extract the URL for downloading the image.svg. The error message reads "NoSuchElementException." Below is a snippet of my code: ((J ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Break down the text of a paragraph into separate words, placing each word within its own span element, and then add animations

I am facing an issue with my paragraph element that has the display property set to hidden. I have split each word of the paragraph and placed them inside individual span elements. My goal is to create an effect where each word comes from different locatio ...

While working on my Laravel and Vue.js project, I encountered the following error message: "Module not found: Error: Can't resolve './vue/app' in 'C:vue odolist esourcesjs'"

Running into an issue where the app.vue file cannot be found in the app.js. I'm using Laravel version "8.31.0" and VueJS version "^2.6.12". Any assistance would be highly appreciated. The content of app.js is: require('./bootstrap'); impor ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

"Encountering an Invalid hook call error with React-Leaflet v4 and Next.js 13

I am facing an issue following my update of Next.js from version 12 to 13, which also involved updating React from 17 to 18 and react-leaflet from 3 to 4. Within this component: ` function ChangeView({ center }) { const map = useMap(); map.setView( ...

The function array.filter is returning the complete object rather than a single value

I'm facing an issue with a function that filters an array. My goal is to retrieve only the string value, not the entire object. However, I keep getting back the entire object instead of just the string. Interestingly, when I switch the return state ...

What is the best way to enable object references in Node modules?

I've been working on my Express.js web app and I've realized that as I extract parts of my code from the main app.js file into separate modules, I sometimes need to access objects from the main file. I'm trying to figure out the best way to ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...

Why isn't the click event triggering MVC 5 client-side validation for ajax posts?

To incorporate client-side validation with a click event for ajax posts, I followed a guide found at the following URL: Call MVC 3 Client Side Validation Manually for ajax posts My attempt to implement this involved using the code snippet below: $(&apos ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

angular: handling duplicates in ng-repeat

Here is the JSON data: streams = [{ id: 0, codec_type: 'video', content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' }, { id: 1, codec_type: 'audio', content: '5.1(side) - cze - undefined' }, ...

What could be causing the JSF ajax status success to fail in Chrome?

Whenever I trigger an action in my ManagedBean, I also initiate a JavaScript function via JSF ajax to display a loading popup while the action is being processed. This functionality works flawlessly in Firefox, however, it seems to encounter issues in Chro ...