Loop through Array and return result into Array

17.1k views Asked by At

I have this array:

var shareholders = [“name1”, “name2”, “name3”];

This is function from HPSM that is fetching data from that array:

function getShareholders(RECORD)
 {
  var fShareholder = new SCFile("device");
  var rc = fShareholder.doSelect("logical.name=\"" + RECORD + "\"");
  if (rc == RC_SUCCESS)
  {
    print(fShareholder.shareholder_contacts);
    return fShareholder.sharholder_contacts;
    }
 return null;
}

It returns them in array form but I need it to fetch one by one:

var users = new Array();
users[0] = “name1”
users[1] = “name2”
….

I have tried them to loop through for loop but without success.

4

There are 4 answers

0
Mihai Alexandru-Ionut On BEST ANSWER

You can use forEach function, which accepts a callback function.

forEach method executes a provided function once for each array element.

Syntax:

arr.forEach(function callback(currentValue, index, array) {

}[, thisArg]);

var shareholders = ['name1', 'name2', 'name3'];
var users=new Array();
shareholders.forEach(function(item,i){
  users[i]=item;
});
console.log(users);

2
Valentin Klinghammer On

Are you looking for the map function?

var shareholders = ['name1', 'name2', 'name3'];
var users = shareholders.map(function (user){
  return user; // Do transformation here
});
console.log(users);
0
Fahad Nisar On

Since you need to fetch the array items one by one, you can use Iterator here like this:

function makeIterator(array) {
    var nextIndex = 0;

    return {
       next: function() {
           return nextIndex < array.length ?
               {value: array[nextIndex++], done: false} :
               {done: true};
       }
    };
}

Once initialized, the next() method can be called to access key-value pairs from the object in turn:

var it = makeIterator([“name1”, “name2”, “name3”];);
console.log(it.next().value); // 'name1'
console.log(it.next().value); // 'name2'
console.log(it.next().value); // 'name3'
console.log(it.next().done);  // true

you can check the details here :

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators. (This example is also from the link.)

0
JohnPion On

Use es6 deconstruction to spread the Array shareholders. Such as

let [user1, user2] = shareholders;// user1 equals shareholders[0] user2 equals shareholders[1].