Reputation:
I know this has been asked multiple times but none of the answers I've seen help. So here's my problem.
I have an array that get's dynamically populated depending on what is selected from a list. At times, the array values that are pushed will have multiple values that are the same. I want to take the values of that array, find if that value already exists in the array, and push it to a new array. I have two global arrays that are defaulted to empty.
//Global arrays
var water_pipes_size_array = [];
var new_water_pipes_size_array = [];
An example of what the water_pipes_size_array
would look like is this:
[0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
What I'm trying to do is search through this array and find any duplicate values and push them into the new_water_pipes_size_array
. However, what I have is not working. I am still getting an empty array.
for(var j = 0; j < water_pipes_size_array - 1; j++){
if(water_pipes_size_array[j + 1] == water_pipes_size_array[j]){
new_water_pipes_size_array.push(water_pipes_size_array[j]);
}
}
console.log(new_water_pipes_size_array);
Can anyone show me what I'm doing wrong and provide some feedback on how to fix it?
Upvotes: 2
Views: 44
Reputation: 2577
If you can use jQuery there is nice way to achieve that
var water_pipes_size_array = [0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var new_water_pipes_size_array = [];
new_water_pipes_size_array=$.map( water_pipes_size_array, function( value,index ) {
return water_pipes_size_array[index+1]==value ? value : null;
});
console.log(new_water_pipes_size_array);
Upvotes: 0
Reputation: 16056
I think you mean to put water_pipes_size_array.length
in your for loop instead of water_pipes_size_array
. Also, since you're starting at 0 you don't need to subtract 1:
for(var j = 0; j < water_pipes_size_array.length; j++){
if(water_pipes_size_array[j + 1] == water_pipes_size_array[j]){
new_water_pipes_size_array.push(water_pipes_size_array[j]);
}
}
The logic is all wrong though. If you just want to eliminate duplicates, try this:
for (var j = 0; j < water_pipes_size_array.length; j++) {
if (new_water_pipes_size_array.indexOf(water_pipes_size_array[j]) == -1) {
new_water_pipes_size_array.push(water_pipes_size_array[j]);
}
}
Upvotes: 3