0

I'm struggling with this kata that instructs me to create an array from a nested listed. I can find explanations for how to do this using Java but that's still a bit confusing for me.

This is what I've got so far...

function listToArray(list) {
  var listArray = [];
  for (var i = 0; i < list.length; i++) {
    listArray[i] = list.value(i);
  };
  return listArray;
};

The test cases...

var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

Test.assertSimilar(listToArray(list1), [1, 2, 3]);
Test.assertSimilar(listToArray(list2), ["foo", "bar"]);

Thanks for the help!

4 Answers 4

4

This is simply a linked list pointer chase:

function listToArray(list) {
  var listArray = [];
  while (list !== null) {
    listArray.push(list.value);
    list = list.next;
  }
  return listArray;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Painfully simple. Thank you for your answer. Can you explain more about what a linked list pointer chase is or point me to where I can learn about it? A quick google search didn't show much.
1

Another solution using recursion:

var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

function convertToArray(list, result) {
  result.push(list.value);
  list.next && convertToArray(list.next,result);
  return result;
}

console.log(convertToArray(list1,[]));
console.log(convertToArray(list2,[]));

Comments

1

Do it with recursion

function listToArray(list) {
  var res = [];
  Object.keys(list).forEach(function(k) {
    if (typeof list[k] == 'object' && list[k] !== null)
      [].push.apply(res, listToArray(list[k]));
    else if (list[k] !== null)
      res.push(list[k]);
  });
  return res;
};

var list1 = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: null
    }
  }
};
var list2 = {
  value: "foo",
  next: {
    value: "bar",
    next: null
  }
};

console.log(listToArray(list1));
console.log(listToArray(list2));

Comments

1

You just have to dig deeper into the object until you reach the null point.

var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

function listToArray(list) {
  var curr = list, arr = [];
  while (curr != null) {
    arr.push(curr.value);
    curr = curr.next;
  }
  return arr;
}

console.log(listToArray(list1));
console.log(listToArray(list2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.