Basically I have an array where there are similar items close by, but I would like to find a way where I leave these items that are the same apart from each other ex:
var array = [1,2,3,3,4];
var myWishArray = [1,2,3,4,3];
||
var myWishArray = [3,2,3,4,1];
||
var myWishArray = [3,2,3,1,4];
...
CodePudding user response:
If it's enough that two equal numbers are never neighbors, then you can
- sort the list
- fill a new array with these numbers in two passes, leaving a space of one
a = [1, 1, 1, 1, 2, 3, 2, 3, 4, 4, 4];
a.sort();
b = Array(a.length);
for (i = 0; i < a.length; i ) {
if (i * 2 < a.length) {
b[i * 2] = a[i];
} else {
start = i - Math.ceil(a.length / 2)
b[start * 2 1] = a[i];
}
}
console.log(b);