Home > Enterprise >  For loop to iterate only the first element of the array
For loop to iterate only the first element of the array

Time:12-09

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;
        }
      }
      

CodePudding user response:

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
  }
}

CodePudding user response:

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

  • Related