Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript- is there a way to destroy all elements of an array by one command? [duplicate]

Tags:

javascript

my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.

var Passengers = new Array();

function FillPassengers(count){
    for(var i=0;i<count;i++)
        Passengers[i] = i;
}

I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?

like image 382
ismail atkurt Avatar asked Apr 26 '13 14:04

ismail atkurt


People also ask

How do you remove all duplicates from an array of objects?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you get all unique values remove duplicates in a JavaScript array?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values.

How do you get rid of repeated values in an array?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

What do you use for removing duplicate elements from an array in JS?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.


1 Answers

You can simply do this to empty an array (without changing the array object itself):

Passengers.length = 0;

Or, with your code:

function FillPassengers(count){
    for(var i=0;i<count;i++)
        Passengers[i] = i;
    Passengers.length = count;
}
like image 172
Ted Hopp Avatar answered Oct 11 '22 19:10

Ted Hopp