Iterate through linked list JavaScript

First of all, although the idea of using reduce is indeed beautiful, I must say that the result is not so good, because the resulting nodes have a field "next" where the value is and a field "value" where the next is, i.e. they are swapped. So let's fix that:

function removeKFromList(l, k) { let list = l.reduceRight((value, next)=>({value: next, next: value}), null); console.log(list); }

Secondly, the name of that function is awful, it should be named "arrayToLinkedList" or something more suggestive. Also, logging the result does not make sense, we should return it instead. Moreover, the parameter k is simply unused. Fixing those things:

function arrayToLinkedList(array) { return array.reduceRight((prev, cur) => ({ value: cur, next: prev }), null); }

Now, let's work on how to iterate over this. What do you think? I will give some hints because giving the answer directly probably won't help you learn much:

Observe that the linked list itself is:

  • Either the value null, or
  • A plain object with two fields, one field "value" which can be anything, and one field "next" which is a linked list.

Observe that the above (recursive) definition is well-defined and covers all cases.

Now, use that to your assistence. How do you get the first value? That would be simply myList.value, right? Now how do I get the second value? By applying .next, we get the next linked list, and so on. If next is null, you know you have to stop.

Let me know if you need further assistance.


EDIT: I noticed that you're looking for the right way to make an iterating method on lists with an idea of "adding it to the prototype" or something. So, about that:

To add an instance method by a prototype, you'd need your linked lists to be a class. That would be overcomplicating, unless you really have a good reason to define a class for this (which would be creating several methods and utility things around it).

It is much better, in my opinion, to just define a function that takes one linked list as the first parameter and a callback function as the second parameter, similarly to lodash's .each:

I'd say this would be the most "javascriptonic" way to do it.