skip to Main Content

I have the below JSON, which is linked to a google calendar. The function setAllEvenDates(arrEvents) loops through all the array but instead of giving the first item of the array give me the last. My intention is to get the first item of the array. How do I achieve that?

var arrElements = [
      { "name": "Electron", "eventdate": "" },
      { "name": "Falcon 9 B5", "eventdate": "" },
      { "name": "New Shepard", "eventdate": "" },
      { "name": "SpaceShipTwo", "eventdate": "" },
      { "name": "Gaofen 14", "eventdate": "" }
    ];

    function setAllEvenDates(arrEvents) {
      for (var i = 0; i < arrEvents.length; i++) {      
        setEventDate(arrEvents[i].name, arrEvents[i].eventdate);
        break;
        }
      }
      

2

Answers


  1. You can get the first item of the array without a for loop.

    var arrElements = [
          { "name": "Electron", "eventdate": "" },
          { "name": "Falcon 9 B5", "eventdate": "" },
          { "name": "New Shepard", "eventdate": "" },
          { "name": "SpaceShipTwo", "eventdate": "" },
          { "name": "Gaofen 14", "eventdate": "" }
        ];
        
    const firstElement = arrElements[0]
    console.log(firstElement)

    Using the for loop you are scrolling the entire array, but is not nececcary if you need only a specific element knowing what element is. You can get any element using array[index] where the index is from 0 to array.length – 1

    Login or Signup to reply.
  2. You don’t even need to define a function for performing setEventDate() method.

    You can do,

    var arrElements = [
      { name: "Electron", eventdate: "" },
      { name: "Falcon 9 B5", eventdate: "" },
      { name: "New Shepard", eventdate: "" },
      { name: "SpaceShipTwo", eventdate: "" },
      { name: "Gaofen 14", eventdate: "" },
    ];
    
    setEventDate(arrEvents[i].name, arrEvents[i].eventdate); //This line will do your job without loop.
    

    If you really want to use the loop,

    var arrElements = [
      { name: "Electron", eventdate: "" },
      { name: "Falcon 9 B5", eventdate: "" },
      { name: "New Shepard", eventdate: "" },
      { name: "SpaceShipTwo", eventdate: "" },
      { name: "Gaofen 14", eventdate: "" },
    ];
    
    function setAllEvenDates(arrEvents) {
      for (var i = 0; i < 1; ) {// no need to crawl through whole array
        setEventDate(arrEvents[i].name, arrEvents[i].eventdate);
        // no need of break statement
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search