Creating a singly linked list in JavaScript that behaves like a single indexed array

I am faced with an array structure like this:

    var arrays = [
  {
    "value": "$6"
  },
  {
    "value": "$12"
  },
  {
    "value": "$25"
  },
  {
    "value": "$25"
  },
  {
    "value": "$18"
  },
  {
    "value": "$22"
  },
  {
    "value": "$10"
  }
];

My goal is to transform this array into a single indexed array that looks like the following:

[{
    "value": "$6",
    "Next": {
        "value": "$12",
        "Next": {
            "value": "$25",
            "Next": {
                "value": "$25",
                "Next": {
                    "value": "$28",
                    "Next": {
                        "value": "$22",
                        "Next": {
                            "value": "$10"
                        }
                    }
                }
            }
        }
    }
}]

I am looking for a way to push the elements of the second array into the first array in the format shown above using JavaScript linked lists.

Answer №1

Utilizing the `Array#reduce` method, transform the given array into a linked list where each iteration creates an object/node and passes the reference to `next` for the next iteration. It is essential to maintain a reference to the `root/head` object as we traverse through the linked list.

var arrays = [{
    "value": "$6"
  },
  {
    "value": "$12"
  },
  {
    "value": "$25"
  },
  {
    "value": "$25"
  },
  {
    "value": "$18"
  },
  {
    "value": "$22"
  },
  {
    "value": "$10"
  }
];
var root = {};
arrays.reduce((acc, { value }) => {
  acc.next = { value };
  return acc.next;
}, root);
var result = [root.next];
console.log(result);

We trust this explanation serves you well!

Answer №2

This code snippet will process the array in a reverse direction, storing the previous value and appending it to the current one before returning the final output.

Give it a try!

function processData(data){
  var result = [];
  var length = data.length;
  var prevValue = {};
  for(var index = length-1; index >= 0; index--){
    var tempObj = {};
    tempObj["value"] = data[index].value;
    if(index !== length){
       tempObj["Next"] = prevValue;
    }
    prevValue = tempObj;
  }
  result.push(prevValue);
  return result;
}

Answer №3

give this a shot

let list=[];
for(let x=0; x<elements.length; x++){ 
   list.push(
      {"content":elements[x]["content"], "following":elements[x+1]}
)}

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

Is there a way to populate rows in a data table on subsequent pages using JavaScript?

Here is the ajax function I have written to change values of a row on one page while updating the total on another page of my data table. $.ajax({ type : "Post", contentType : "application/json; charset= ...

Is it possible to use Symbol.iterator in an Object via prototype in JavaScript?

What is the reason behind the inability to add Symbol.iterator to an Object in this way? Object.prototype[Symbol.iterator]; let obj = {num: 1 , type : ' :) '} for (let p of obj) { console.log(p); } // TypeError: obj is no ...

What is the best way to focus on Virtual Keys with jQuery keypress?

Looking to target virtual keys in order to detect when they are pressed using jQuery. Specifically interested in targeting the mute button. I have come across some references that mention the need to target virtual keys, but haven't found any clear i ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

What's preventing the mobx @computed value from being used?

Issue: The computed value is not updating accordingly when the observable it is referencing goes through a change. import {observable,computed,action} from 'mobx'; export default class anObject { // THESE WRITTEN CHARACTERISTICS ARE COMPUL ...

Is converting a List to an Array more efficient in terms of iteration?

Benchmark Analysis: List vs. List To Array Transformation var list = new List<string>(Size); for (int i = 0; i < Size; i++) list.Add(i.ToString()); var b = new Benchmark(); b.Test("TestListIteration", () => { c = 0; for (int i = 0; i &l ...

How to access a function defined within the jQuery ready function externally

My ASPX page content:- <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.8.2.custom.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready ...

A guide to implementing a dynamic limit in ng-repeat using AngularJS

I'm looking to dynamically set a limit in my ng-repeat. The goal is to limit the number of items displayed to 1 when the window width is less than 750px. Below is the function in my controller: $scope.$watch('window.innerWidth', function() ...

Create a unique command that will run regardless of the success or failure of the command before

Even if a preceding command fails, the end command is still executed. For example: browser.waitForElementIsVisible("non-existing-item", 500).end() I am looking to create a custom command that always gets called in the same way as the end command. When I t ...

What is the best way to generate a fresh object using an existing object in Javascript?

Struggling with generating a new object from the response obtained from an ajax call in JavaScript app. The data received is an array of objects, shown below: { "items": [ { "id": "02egnc0eo7qk53e9nh7igq6d48", "summary": "Learn to swim ...

problem with the video pathway in the javascript document

I'm currently in the process of putting together a Video gallery playlist using HTML, CSS, and JavaScript. So far, I've set up the html and css files along with two js files. The first js file contains all the video information as shown here: ...

Calculate the total and average of related values with the associative array having identical keys

I'd like to build upon the discussion located at Associative array, sum values of the same key. https://i.sstatic.net/YO7BO.jpg The original poster inquires: Instead of having the key "Conference" repeating 3 times. I want to have it just once an ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

Stop the initial expansion of the first accordion with JavaScript on page load

I have a simple accordion created using only pure javascript without jQuery and Pure CSS. Everything is functioning correctly, but the problem I am facing is that the first accordion is automatically expanded when the page loads. I have tried various metho ...

In Chrome, the `Jquery $('input[name=""]').change(function will not be triggered unless there is an unhandled error following it

Here is a script that I've created to make certain inputs dependent on the selection of a radio button. The 'parent' input in this case is determined by the radio button choice. Upon document load, the script initially hides parent divs of ...

Failure to trigger AJAX Success or Error Events

I'm struggling to understand why this code isn't working or find any relevant resources. When I check the json object in Firebug, it either returns success: false or success: true from the post request, so I'm confused as to why the function ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...

How can we use regular expressions to identify strings that do not begin with a letter or number?

Imagine having the string below: Lorem #test ^%#test ipsum#test dolor #test sit #testamet. ^^^^^ ^^^^^ What regular expression should be used to specifically select the highlighted #test instances? It is important to only c ...

Various conditional statements based on the dropdown menu choice

I currently have a basic dropdown menu on my webpage that enables users to switch between viewing Actual or Planned dates/times in a table (I am utilizing the controller as syntax): <select ng-model="trip.viewType"> <option value="actual"> ...

The reason why the script and div tags are so common in HTML is because they serve different purposes. However, it's

Hey there, friend! I've searched on baidu.com, cnds, and stack overflow, but couldn't find an answer. I have two questions: "why can script and div tags be used so much in HTML?" and "why is there only one html and body tag in HTML?" For example: ...