1

I want to create a function in Javascript which takes an array as argument and returns a list of objects. I have an array like this:

var arr= [10,20,30];
console.log(listFunction(arr));

The result should look like this:

{'val':10, 'restList':{'val':20, 'restList':{'val':30,'restList':'null'}}}

I have tried the forEach() function:

function listFunction(parentArr) {
    var listOfObjects = [];
    parentArr.forEach(function (entry, thisArg) {
        var singleObj = {}
        singleObj['val'] = entry;
        singleObj['restList'] = singleObj;
        listOfObjects[thisArg] = singleObj;
    });
    return listOfObjects;
};
3
  • Like a Linked-List or a functional Lisp-like list? Commented Mar 31, 2015 at 13:16
  • @ryanyuyu a list of node and successor. yes like Linked-list Commented Mar 31, 2015 at 13:19
  • It would be easier if the inner most restList should be {} instead of null. Commented Apr 1, 2015 at 0:24

2 Answers 2

4

You need to use a recursive function:

function listFunction(arr){

   if(arr.length == 0){
       return null;
   }else{
       return {val: arr[0], restList: listFunction(arr.slice(1,arr.length))};
   }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

You can send the next position of array. But you need create another function. function listFunction(arr, index)... And you need to increase the index in each step.
Quick note: arr.length isn't needed in the slice function. If the second parameter is missing, it defaults to the length of the array.
0

This is the Lisp-style recursive list algorithm.

var recursiveList = function (array) {
  return recursiveListHelper(arr, {});
};

var recursiveListHelper = function (array, obj) {
  if (array.length === 0) //stopping condition
    return null;

  var car = array[0];       //current element
  var cdr = array.slice(1); //rest of list
  obj = {val: car};
  obj.restList = recursiveListHelper(cdr, obj);
  return obj;
};

You mentioned that you wanted to avoid using Array.slice. This solution uses array indexing instead of splitting into subarrays.

var recursiveIndexed = function (array) {
  return recursiveIndexedHelper(array, {}, 0);
};

var recursiveIndexedHelper = function (array, obj, index) {
  if (index == array.length)
    return null;

  var car = array[index];
  obj = {val: car };
  obj.restList = recursiveIndexedHelper(array, obj, index + 1);
  return obj;
};

A plunker as example.

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.