-2

I got two arrays. One is blank and another with data. I pick random candidates and paste them inside my blank array.

As i have already picked those candidates,i dont want their name to be picked again as well as I dont want to loose their index position in the original array. To avoid picking again, i set name = undefined. Now what happens is my duplicated array is also updated with undefined.

if you run the below code, toggling below line and check the selectedcandidates array it will give better info.

 candidates[candidateIndex[i]].name= undefined;

How can i copy element into other array and update the original array, without affecting copied array.Thanks in advance.

<!DOCTYPE html>   
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button onclick="selectCandidate()">Click Here !!!</button> <script>
    var selectedCandidate=[];
        var candidates = [
            {name:"Alpha",
             age:"21"
            },
            {name:"Beta",
             age:"21"
            },
            {name:"Gamma",
             age:"21"
            },
            {name:"Albert",
             age:"21"
            },
            {name:"Alaks",
             age:"21"
            },
            {
             age:"21"
            },
            {
             age:"21"
            }
           ];
        function selectCandidate(){
            var candidateIndex = [];
            for(i =0; i<2; i++){
                var randomnumber = generateRandomNumber();
                if(candidateIndex.indexOf(randomnumber) && candidates[randomnumber].name != undefined){
                candidateIndex.push(randomnumber);
                }
                else{
                i--;
                }
            }
            var selectthiscandidate;
            for(i=0; i< 2; i++){
                selectthiscandidate = candidates[candidateIndex[i]];
                selectedCandidate.push(selectthiscandidate);
                candidates[candidateIndex[i]].name= undefined;
            }         
            console.log(selectedCandidate);
            console.log(candidates);  
        }
 function generateRandomNumber(){
            return Math.floor((Math.random() * candidates.length-1) + 1);
        }



    </script>
</body>
</html>
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83
  • you push to the `selectedCandidate` just a reference to original object from `candidates` – MysterX Sep 13 '15 at 10:10
  • Related to [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – Nico Hauser Sep 13 '15 at 10:11
  • @MysterX is it a question to me or answer. Sorry, cant understand. – Alaksandar Jesus Gene Sep 13 '15 at 10:14
  • 1
    this was a part of the answer. So do selectthiscandidate = {name: candidates[candidateIndex[i]].name, age : candidates[candidateIndex[i].age]}; – MysterX Sep 13 '15 at 10:19
  • What about removing the entire object from the candidates array? I believe that would be easier to manage. –  Sep 13 '15 at 10:34

3 Answers3

0

Your issue is with the line

selectedCandidate.push(selectthiscandidate);

because it pushes a reference to the object inside of the selectedCandidate array, not a clone of the object. To solve this, simple clone the object. You can do that with libraries like jQuery ($.extend) or using pure JavaScript and JSON object. So your line should be something like this:

selectedCandidate.push(JSON.parse(JSON.stringify(selectthiscandidate)));

Hope that helps ;)

metal03326
  • 1,213
  • 2
  • 13
  • 15
0

Changed My code as per @MysterX guidelines and it worked. Credits to @MysterX

  for(i=0; i< 2; i++){
                    selectthiscandidate ={};
                    selectthiscandidate ={name:candidates[candidateIndex[i]].name,age:candidates[candidateIndex[i]].age}
                    selectedCandidate.push(selectthiscandidate);
                candidates[candidateIndex[i]].name= undefined;    
            }
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83
0

The following code removes the object entirely from the original array (press "Run code snippet" multiple times to print different results):

var candidates = [{
  name: "Alpha",
  age: "21"
}, {
  name: "Beta",
  age: "21"
}, {
  name: "Gamma",
  age: "21"
}];

document.write('<p>"candidates" before selection:</p>');
print(candidates);
document.write('<p>Selection (returns a new array):</p>');
print(selectSome(candidates, 2));
document.write('<p>"candidates" after selection:</p>');
print(candidates);

function selectSome (source, n) {
  var i = 0;
  var total = source.length;
  var selected = new Array(n);
  while (i < n) {
    selected[i++] = selectOne(
      source, Math.floor(
        Math.random() * total
      )
    );
  }
  return selected;
}

function selectOne (source, i) {
  if (source[i] === null) {
    // already selected, retry with i + 1
    return selectOne(source, ++i % source.length);
  }
  else {
    // candidate found, replace it with null and return it
    return source.splice(i, 1, null)[0];
  }
}

function print (o) {
  document.write(
    '<pre>' + JSON.stringify(o) + '</pre>'
  );
}