Home > Blockchain >  How can I loop list an array containing object by starting from 1 to the last instead of starting fr
How can I loop list an array containing object by starting from 1 to the last instead of starting fr

Time:12-01

const array=[
{
    "firstname":"akira",
    "lastname":"laine",
    "number":"090897878",
    "like":["pizza","coding","points","brownie"]
},{
    "firstname":"harry",
    "lastname":"pooter",
    "number":"070896778",
    "like":["Hogwarts","magic","Hagrid"]
},{
    "firstname":"sherlock",
    "lastname":"Holmes",
    "number":"080896975",
    "like":["Intriguing","case","Voilin"]
},{
    "firstname":"Kristian",
    "lastname":"Vos",
    "number":"080894575",
    "like":["Javascript","Gaming","Foxes"]
}  

]

I used recursive function to perform the task but no result yet

    function names(array,end) {
  if(array.length>end){
    console.log(array)
    return names(array-1,end)    
  }
    

} names(array,1)

i am stock with this for days now. I need help on this. You when you loop through the array containing object it list out the element in the array starting from zero to the last element in the array. My problem now is that how can loop through it starting from 1 to the last element in the array instead of zero.

CodePudding user response:

As Daniel says:

    // entire list starting a '0'
    for (let i=0; i<array.length; i  ) { console.log(JSON.stringify(array[i])) }
    console.log();
    // entire list starting a '1'
    for (let i=1; i<array.length; i  ) { console.log(JSON.stringify(array[i])) }

Or as an alternative:

    var newArray = [...array];
    newArray.shift();
    console.log();
    for (let i=0; i<newArray.length; i  ) { console.log(JSON.stringify(newArray[i])) }

If you only wanted the lastname and likes of that entry:

    console.log();
    for (let i=1; i<array.length; i  ) { 
      console.log(`${array[i].lastname} likes: ${array[i].like}`);
    }

CodePudding user response:

for (let i=1; i<array.length   1; i  ) { 
   console.log(array[i-1], i)   
}

This was able to solve the problem for me. Thanks everyone

  • Related