0

Hello i'd like to ask a simple question, here example code

<script>
var mycars=["Saab","Volvo","BMW","Honda","BMW","Suzuki","Volvo","Toyota","Saab","Nissan"];
var count=0;
for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br>");
count++;
}
document.write("Total Data is "+count);
</script>

from example above it will output : Saab Volvo BMW Honda BMW Suzuki Volvo Toyota Saab Nissan Total Data is 10

how if i want to call each cars just once like BMW,Volvo and Saab it's called twice, and i want it called once then the total data will 7.

how can i give boolean condition for this? so it wont called again? thanks

Koyix
  • 181
  • 1
  • 3
  • 17

1 Answers1

1

You could filter out the duplicates:

mycars = mycars.filter(function(car, index, cars){ return cars.indexOf(car, index + 1) === -1; });

After you do this, all but the last instance of each distinct value will be removed from the array. If you need to keep the original array, then use a new variable for the filtered one:

var unique_cars = mycars.filter(function(car, index, cars){ return cars.indexOf(car, index + 1) === -1; });

Note that you need to shim Array.prototype.indexOf in older browsers.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • how about if i wont to erase it, but give some condition that some car has been called ? – Koyix Feb 23 '14 at 04:04
  • maybe if it can used by boolean condition? – Koyix Feb 23 '14 at 04:04
  • You can create an object to keep track of which cars you've written so far. Before your loop: `var is_car_written = {};`, then in your loop: `if (is_car_written[mycars[i]]) { is_car_written[mycars[i]] = true; document.write(mycars[i] + "
    "); }'
    – Paul Feb 23 '14 at 04:08