2

I need insert data from array contacts to array data one by one after click button. After click button insert contacts[0], after another click insert contacts[1] without contacts[0] and contacts[2...] after next click insert contacts[2]...

<button id="submit-btn" onclick="myFunc()">Search</button>

  const contacts = ['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366',
                    'Dianne:2434356','Amy:2356546','Andreu:23546457'];


    var data = [];
    function myFunc(){
            //var res = contacts.filter(f => !data.includes(f));

        for ( let x = 0; x < contacts.length; x++ ){
            data.push(contacts[x]);
        }
    }

This will save whole contacts.

2
  • do you want to keep the contacts array intact or you want to remove those elements from contacts after inserting elements into data array? Commented Dec 30, 2018 at 16:43
  • keep original contacts Commented Dec 30, 2018 at 16:45

2 Answers 2

3

Use shift along with a check that clicks are not going beyond length of array. if you don't add check than after exceeding array length it will keep adding undefined

You can use a global variable as index tracker and keep updating and every time you click on button and push values in your data array. But in JS world it is generally considered as an anti-pattern to use global variables.

const contacts = 
['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366','Dianne:2434356','Amy:2356546','Andreu:23546457'];

    var data = [];
function myFunc(){
  if(contacts &&contacts.length > 0)
  {
    data.push(contacts.shift());
    console.log(data)
  } else {
    console.log('No more contacts in your list')
  }
}
<button id="submit-btn" onclick="myFunc()">Search</button>

Sign up to request clarification or add additional context in comments.

3 Comments

maybe just add a fail safe mechanism that index doesn't go beyond array items.
but shift() method remove elements from contacts array this is what I dont want
@Martin yes it does. but you have all your data now in data array. anyway you can have a copy of original array and use shift on that. any time concatenation of data+contacts will give you your original data back.
2

Just use a global counter value, and in your function, increment it and push to the array:

 

const contacts = ['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366','Dianne:2434356','Amy:2356546','Andreu:23546457'];
var counter = 0;
var data = [];
function myFunc() {
    if (!(counter++ > contacts.length)) {
        data.push(contacts[counter]);
        counter++;
        console.log(data);
    } else {
        alert("No more contacts left!");
    }
}
 

<button id="search-btn" onclick="myFunc()">Search</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.