JSFiddle - React, Tailwind, and code Playground
by karin
HTML
<table width="100%" border="1" cellpadding="5">
<thead>
<tr>
<th>array a</th>
<th>a length</th>
<th>result</th>
<th>result length</th>
</tr>
</thead>
<tbody>
<tr>
<td id='demo'></td>
<td id="demo2"></td>
<td id='demo3'></td>
<td id='demo4'></td>
</tr>
</tbody>
</table>
JavaScript
var a = [5,8,1,6,8,1];
var result =[];
var demo = document.getElementById('demo');
var demo2 = document.getElementById('demo2');
var demo3 = document.getElementById('demo3');
var demo4 = document.getElementById('demo4');
//first loop
for (var i = 0; i < a.length; i++) {
for(var y = 0; y < a.length; y++){
//if location i is different but the value is the same
//alert(a[i]+' '+a[y]);
if((a[i]===a[y])&&(i!==y)){
//alert(a[i]+'|'+'i:'+i+' y:'+y+'<br/>remove pos: '+i+'add:'+a[i]);
var p=parseInt(a[i]);//store duplicate in a variable
a.splice(i,1);//remove duplicate from an array
var u=parseInt(a[y]);//store second duplicate in a variable
a.splice(y,1);//remove second duplicate from an array
//add doubles to result
result.splice(0,0,p);
result.splice(0,0,u);
}
}
}
//display array
for(var j=0;j<a.length;j++){
demo.innerHTML+=a[j]+' ';
}
demo2.innerHTML=a.length;
//display result
for(var r = 0; r < result.length; r++){
demo3.innerHTML+=result[r]+' ';
}
demo4.innerHTML=result.length;