Javascript: How to clear undefined values from an array - javascript

I'm trying to loop through an array and delete and skip the elements until only one is existing. i've tried splicing but it messes up my loop because the element from arr[1] then becomes arr[0] etc.
Let's say there are 10 people. I'd like to remove person 1 then keep person 2 then remove person 3 and keep person 4. This pattern will go on until only one is left.
any kind of help will do.

Filter the falsy items:
var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]

you should not change the collection during the iterating, not just JavaScript but all language, define a new array and add those ones you want to delete in it, and iterate that one later to delete from first one.

When you splice, just decrement your loop index.
There were lots of good suggestions, I'll post the code for the different options and you can decide which to use
Decrement index when splicing
http://jsfiddle.net/mendesjuan/aFvVh/
var undef;
var arr = [1,2, undef, 3, 4, undef];
for (var i=0; i < arr.length; i++) {
if ( arr[i] === undef ) {
arr.splice(i,1);
i--;
}
}
Loop backwards http://jsfiddle.net/mendesjuan/aFvVh/1/
var undef;
var arr = [1,2, undef, 3, 4, undef];
for (var i=arr.length - 1; i >=0; i--) {
if ( arr[i] === undef ) {
arr.splice(i,1);
}
}
Copy to new array http://jsfiddle.net/mendesjuan/aFvVh/2/
var undef;
var arr = [1,2, undef, 3, 4, undef];
var temp = [];
for (var i=0; i < arr.length; i++) {
if ( arr[i] !== undef ) {
temp.push(arr[i])
}
}
arr = temp;
Use filter which is just a fancy way to create a new array
var undef;
var arr = [1,2, undef, 3, 4, undef];
arr = arr.filter(function(item){
return item !== undef;
});
At the end of all those examples, arr will be [1,2,3,4]
Performance
IE 11, FF and Chrome agree that Array.splice is the fastest. 10 times (Chrome), 20 times (IE 11) as fast as Array.filter. Putting items into a new array was also slow when compared to Array.slice. See
http://jsperf.com/clean-undefined-values-from-array2
I am really surprised to see IE lead the pack here, and to see Chrome behind FF and IE. I don't think I've ever run a test with that result.

Loop backwards. (Removing items will thus not affect the indexes of elements not yet processed.)

If by any chance you're using CoffeeScript then to remove undefined from Array do this
values = ['one', undefined]
values = (item for item in values when item != undefined)
values
/* => ['one'] */

Surprisingly, nobody have answered the best and correct way:
Create new array
Iterate on the old array and only push the elements you want to keep to the new array
some credit goes to #nnnnnn comment

Not gathering exactly what you are trying to achieve, but I feel you are relying on the position index of an item in the array to continue with your program. I would in this case suggest a hashed array, i.e., a Key<>Value pair array.
In which case, arr["2"] always points at the item you had placed in it originally. Thus you can logically/numerically loop through, while not worrying about changes in position.
Beware of the Type Conversion risk and pitfalls!

Your best bet is to create a duplicate of the array, then splice from the original.
Or just go using a collection (key->value) and just delete the key eg
People = {a: "Person A", b: "Person B", c:"Person C"};
delete People.a;
delete People.c; //now the People collection only has 1 entry.
You can replace a,b,c with numbers just using it as an example,
People = {0: "Person A", 1: "Person B", 2:"Person C"};
delete People[0];
delete People[1];

this is a sample for you
<script lanauge = "javascript">
var arr = ["1","2","3","4"];
delete arr[1];// arr[1] is undefined
delete arr[2];// arr[2] is undefined
// now arr.length is 4
var todelete = [];
for (i = 0 ; i < arr.length ;i++)
{
if (typeof arr[i] == 'undefined') todelete.push(i);
}
todelete.sort(function(a, b) { return b-a }); // make the indeies from big to small
for (i = 0;i < todelete.length; i ++)
{
arr.splice(todelete[i],1);
}
// now arr.length is 2
</script>

This may not be what you want, but you can easily calculate what the final element at the end of this procedure will be, then just grab it. Assuming that the elements of the array are contiguous and start at arr[0], you can find:
var logBase2OfLength = Math.floor(Math.log(arr.length) / Math.log(2));
var finalElement = arr[(1 << logBase2OfLength) - 1];
Basically, if you take the integer power of 2 that is less than or equal to the number of elements in your array, that is the position of the element that will remain after all of the looping and deleting.

function removeUndefined(array)
{
var i = 0;
while (i < array.length)
if (typeof array[i] === 'undefined')
array.splice(i, i);
else
i++;
return array;
}
EDIT: I wrote this based on the title. Looks like the question asks something completely different.

>If you are getting undefined during deletion of the key-pair, Then to prevent "undefined" you can try code given below to delete key-pair
1) test = ["1","2","3","4",""," "];
2) var delete = JSON.stringify(test);
case1) delete = delete.replace(/\,""/g,'');
or
case2) delete = delete.replace(/\," "/g,'');
or
case3) delete = delete.replace(/\,null/g,'');
3) var result = JSON.parse(delete);

simply
[NaN, undefined, null, 0, 1, 2, 2000, Infinity].filter(Boolean)

while(yourarray.length>1) //only one left
{
// your code
}

Related

How to remove a JavaScript component (object) [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is there a way to empty an array and if so possibly with .remove()?
For instance,
A = [1,2,3,4];
How can I empty that?
Ways to clear an existing array A:
Method 1
(this was my original answer to the question)
A = [];
This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.
This is also the fastest solution.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
Method 2 (as suggested by Matthew Crumley)
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.
Method 3 (as suggested by Anthony)
A.splice(0,A.length)
Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
Method 4 (as suggested by tanguy_k)
while(A.length > 0) {
A.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
Performance
Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.
As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.
The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).
This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
A.length = 0;
Here the fastest working implementation while keeping the same array ("mutable"):
function clearArray(array) {
while (array.length > 0) {
array.pop();
}
}
FYI it cannot be simplified to while (array.pop()): the tests will fail.
FYI Map and Set define clear(), it would have seem logical to have clear() for Array too.
TypeScript version:
function clearArray<T>(array: T[]) {
while (array.length > 0) {
array.pop();
}
}
The corresponding tests:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152
jsPerf offline. Similar benchmark: https://jsben.ch/hyj65
A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:
A.splice(0, A.length);
The answers that have no less that 2739 upvotes by now are misleading and incorrect.
The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].
Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.
This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.
Let's say your mother asks you to empty the trash can.
You don't bring in a new one as if you've done what you've been asked for.
Instead, you empty the trash can.
You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];
Emptying an array object is the easiest thing ever:
A.length = 0;
This way, the can under "A" is not only empty, but also as clean as new!
Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:
while(A.length > 0) {
A.pop();
}
Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:
A.splice(0, A.length);
No, you were asked to empty it:
A.length = 0;
This is the only code that correctly empties the contents of a given JavaScript array.
Performance test:
http://jsperf.com/array-clear-methods/3
a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length) // 97% slower
while (a.length > 0) {
a.pop();
} // Fastest
You can add this to your JavaScript file to allow your arrays to be "cleared":
Array.prototype.clear = function() {
this.splice(0, this.length);
};
Then you can use it like this:
var list = [1, 2, 3];
list.clear();
Or if you want to be sure you don't destroy something:
if (!Array.prototype.clear) {
Array.prototype.clear = function() {
this.splice(0, this.length);
};
}
Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.
You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse.
Imagine you have this array:
var arr = [1, 2, 3, 4, 5]; //the array
OK, just simply run this:
arr.length = 0; //change the length
and the result is:
[] //result
easy way to empty an array...
Also using loop which is not necessary but just another way to do that:
/* could be arr.pop() or arr.splice(0)
don't need to return as main array get changed */
function remove(arr) {
while(arr.length) {
arr.shift();
}
}
There are also tricky way which you can think about, for example something like this:
arr.splice(0, arr.length); //[]
So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array.
Also other ways like simply reassign the array for example:
arr = []; //[]
If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length.
As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like:
Array.prototype.remove = Array.prototype.remove || function() {
this.splice(0, this.length);
};
and you can simply call it like this to empty any array in your javascript application:
arr.remove(); //[]
If you are using
a = [];
Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.
For ex.
var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];
or
a.length = 0;
When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.
Instead of these two solutions are better.
a.splice(0,a.length)
and
while(a.length > 0) {
a.pop();
}
As per previous answer by kenshou.html, second method is faster.
There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(Math.random());
}
for (var j = 0; j < 1000; j++) {
while (arr.length > 0) {
arr.pop(); // this executes 100 times, not 100000
}
}
I have created a new test that works correctly :
http://jsperf.com/empty-javascript-array-redux
Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).
Array.prototype.clear = function() {
this.length = 0;
};
And call it: array.clear();
In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in #tanguy_k's answer above.
(for an intro to the aforementioned tab you can check out here)
Stackoverflow forces me to copy the jsfiddle so here it is:
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]="something"
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.
Use a modified version of Jan's initial suggestion:
var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
A.pop();
}
Terser:
for (let i = A.length; i > 0;A.pop(),i--) {}
Or here's another take:
while(!A[Symbol.iterator]().next().done)A.shift()
A.splice(0);
I just did this on some code I am working on. It cleared the array.
If you use constants then you have no choice:
const numbers = [1, 2, 3]
You can not reasign:
numbers = []
You can only truncate:
numbers.length = 0
To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'
length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
pop() : The pop method removes the last element from an array and returns that returns the removed value.
shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
Example:
var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]
var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];
var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);
refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);
mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);
mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);
Array.prototype.poptill_length = function (e) {
while (this.length) {
if( this.length == e ) break;
console.log('removed last element:', this.pop());
}
};
new Array() | [] Create an Array with new memory location by using Array constructor or array literal.
mainArr = []; // a new empty array is addressed to mainArr.
var arr = new Array('10'); // Array constructor
arr.unshift('1'); // add to the front
arr.push('15'); // add to the end
console.log("After Adding : ", arr); // ["1", "10", "15"]
arr.pop(); // remove from the end
arr.shift(); // remove from the front
console.log("After Removing : ", arr); // ["10"]
var arrLit = ['14', '17'];
console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
function indexedItem( arr ) {
var indexedStr = "";
arr.forEach(function(item, index, array) {
indexedStr += "{"+index+","+item+"}";
console.log(item, index);
});
return indexedStr;
}
slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.
var shallowCopy = mainArr.slice(); // this is how to make a copy
var cloneArr = mainArr.slice(0, 3);
console.log('Main', mainArr, '\tCloned', cloneArr);
cloneArr.length = 0; // Clears current memory location of an array.
console.log('Main', mainArr, '\tCloned', cloneArr);
I'm surprised no one has suggested this yet:
let xs = [1,2,3,4];
for (let i in xs)
delete xs[i];
This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied':
xs
=> Array [ <4 empty slots> ]
[...xs]
=> Array [ undefined, undefined, undefined, undefined ]
xs.length
=> 4
xs[0]
=> ReferenceError: reference to undefined property xs[0]
You can produce an equivalent array with [,,,,] or Array(4)

Delete from array in javascript

3 hours ago, I asked a question in SO , about deleting a part of an object, so I linked this question to it:
delete a part of object in javascript
but now another problem occurred when I deleted from that array.
I use that object to populate a FlexiGrid. but when I delete an item from that object by following code, instead of delete that item , it sets to undefined :( and flexigrid did not accept it for input data.
for (var i = 0; i < Roomdata.length; i++) {
if(Roomdata[i].id = X) {
delete Roomdata[i];
break;
}
}
For example, imagine I have 3 items in Roomdata like this :
{item1, item2, item3}
When I call this code to delete item2 , Roomdata object looks like this :
{item1, undefined, item3}
and this is a bad format to be accepted by flexigrid as input data
Is there any solution ?
Thanks every body and sorry about my bad syntax (I am new in English)
regards , Foroughi
Walk through the array in reverse order, and use .splice to remove the element.
You have to walk in the reverse order, because otherwise you end up skipping elements See below.
for (var i = Roomdata.length-1; i >= 0; i--) {
if (Roomdata[i].id == X) {
Roomdata.splice(i, 1);
break;
}
}
What happens if you don't walk in the reverse order:
// This happens in a for(;;) loop:
// Variable init:
var array = [1, 2, 3];
var i = 0;
array.splice(i, 1); // array = [2, 3] array.length = 2
// i < 2, so continue
i++; // i = 1
array.splice(i, 1); // i=1, so removes item at place 1: array = [2]
// i < 1 is false, so stop.
// array = [2]. You have skipped one element.
What you have is an Array. You should use the splice() method to remove an element from an array, not by deleteing the element.
for (var i = 0; i < Roomdata.length; i++) {
if(Roomdata[i].id = X) {
Roomdata.splice(i, 1);
break;
}
}
Using splice in spite of delete.
Roomdata.splice(i, 0);
splice attribute removes blank string elements, undefined references, NULLs and FALSEs.
it will solve your problem
To remove all of the elements of an array matching a particular value, you can do this:
// Remove all elements in arr[] matching val
for (let i = 0; i < arr.length; i++) {
if (arr[i] === val) {
arr.splice(i--, 1); // Remove arr[i] and adjust the loop index
}
}
Note that this is a forward scan of the array. The decrement of the loop index is necessary so that the loop does not skip the next element after an element is removed.

Creating a limited array with custom methods

I want to create a helper object that will work the following way:
It is an array with a given number of rows, for example let's say it can hold only 3 rows.
It will have an insert method that inserts the a new entry at the first index, and pushes one index down all the rest (new entry is 0, 0 becomes 1, 1-->2 etc..)
and if the array is full to the max number of rows, the last entry drops out.
So I made it the following way:
function limArray(array, maxlength){
this.arr = array;
this.maxlength = maxlength;
this.arr.length = maxlength;
this.insertVal = function(value){ //insert new value and push down the rest
for (var i=maxlength; i>=0; i--) {
this.arr[i] = this.arr[i-1]
};
this.arr[0] = value;
this.arr.length = maxlength;
};
}
My question is, if it's a smart way to make this?
Is it possible to create instance of the Array object itself and modify it to be limited etc..
Any critique / improvement suggestions are welcome!
You could overwrite the push method:
function limArray(array, maxlength){
var push_ = array.push,
slice_ = [].slice;
array.push = function() {
var values = slice_.call(arguments, 0, maxlength - this.length);
return push_.apply(this, values);
}
return array;
}
As #alnorth29 mentioned, you can use unshift to prepend a value. You can overwrite this as well:
function limArray(array, maxlength){
// push like above
var unshift_ = array.unshift;
array.unshift = function() {
unshift_.apply(this, arguments);
this.length = this.length > maxlength ? maxlength : this.length;
return this.length;
}
return array;
}
Of course you can also attach a new property with a more expressive name than unshift:
array.prepend = array.unshift;
If you extend an array instance like this, make sure you only traverse over its elements with a for loop, not with a for...in loop (you should always use for for arrays anyway). Another possibility is to define the property using ECMAScript 5's Object.defineProperty [docs] and set enumerable to false. But it is only supported in newer browsers.
There are other ways to add elements to an array, but I assume you are not going to use them .
Usage:
> var limited = limArray([], 3);
> limited.push(1,2,3,4);
3
> limited
[1, 2, 3]
> limited.push(5)
3
> limited
[1, 2, 3]
> var limited = limArray([], 3);
> limited.unshift(3, 4)
2
> limited
[3, 4]
> limited.unshift(1, 2)
3
> limited
[1, 2, 3]
Update:
I forgot, in case the array passed to the function already exceeds the maximum number of elements, you have to reduce the length:
function limArray(array, maxlength){
array.length = array.length > maxlength ? maxlength : array.length;
//...
return array;
}
This looks fine to me, though you could use the array's unshift method to add values to the start of the array rather than manually updating all of them. This would make it more compact.
function limArray(array, maxlength){
this.arr = array;
this.maxlength = maxlength;
this.arr.length = maxlength;
this.insertVal = function(value){ //insert new value and push down the rest
this.arr.unshift(value);
this.arr.length = maxlength;
};
}
As far as I know there's no built in way for defining the maximum length of an array.

Javascript array sort and unique

I have a JavaScript array like this:
var myData=['237','124','255','124','366','255'];
I need the array elements to be unique and sorted:
myData[0]='124';
myData[1]='237';
myData[2]='255';
myData[3]='366';
Even though the members of array look like integers, they're not integers, since I have already converted each to be string:
var myData[0]=num.toString();
//...and so on.
Is there any way to do all of these tasks in JavaScript?
This is actually very simple. It is much easier to find unique values, if the values are sorted first:
function sort_unique(arr) {
if (arr.length === 0) return arr;
arr = arr.sort(function (a, b) { return a*1 - b*1; });
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) { //Start loop at 1: arr[0] can never be a duplicate
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]
You can now achieve the result in just one line of code.
Using new Set to reduce the array to unique set of values.
Apply the sort method after to order the string values.
var myData=['237','124','255','124','366','255']
var uniqueAndSorted = [...new Set(myData)].sort()
UPDATED for newer methods introduced in JavaScript since time of question.
This might be adequate in circumstances where you can't define the function in advance (like in a bookmarklet):
myData.sort().filter(function(el,i,a){return i===a.indexOf(el)})
Here's my (more modern) approach using Array.protoype.reduce():
[2, 1, 2, 3].reduce((a, x) => a.includes(x) ? a : [...a, x], []).sort()
// returns [1, 2, 3]
Edit: More performant version as pointed out in the comments:
arr.sort().filter((x, i, a) => !i || x != a[i-1])
function sort_unique(arr) {
return arr.sort().filter(function(el,i,a) {
return (i==a.indexOf(el));
});
}
How about:
array.sort().filter(function(elem, index, arr) {
return index == arr.length - 1 || arr[index + 1] != elem
})
This is similar to #loostro answer but instead of using indexOf which will reiterate the array for each element to verify that is the first found, it just checks that the next element is different than the current.
Try using an external library like underscore
var f = _.compose(_.uniq, function(array) {
return _.sortBy(array, _.identity);
});
var sortedUnique = f(array);
This relies on _.compose, _.uniq, _.sortBy, _.identity
See live example
What is it doing?
We want a function that takes an array and then returns a sorted array with the non-unique entries removed. This function needs to do two things, sorting and making the array unique.
This is a good job for composition, so we compose the unique & sort function together. _.uniq can just be applied on the array with one argument so it's just passed to _.compose
the _.sortBy function needs a sorting conditional functional. it expects a function that returns a value and the array will be sorted on that value. Since the value that we are ordering it by is the value in the array we can just pass the _.identity function.
We now have a composition of a function that (takes an array and returns a unique array) and a function that (takes an array and returns a sorted array, sorted by their values).
We simply apply the composition on the array and we have our uniquely sorted array.
This function doesn't fail for more than two duplicates values:
function unique(arr) {
var a = [];
var l = arr.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If a[i] is found later in the array
if (arr[i] === arr[j])
j = ++i;
}
a.push(arr[i]);
}
return a;
};
Here is a simple one liner with O(N), no complicated loops necessary.
> Object.keys(['a', 'b', 'a'].reduce((l, r) => l[r] = l, {})).sort()
[ 'a', 'b' ]
Explanation
Original data set, assume its coming in from an external function
const data = ['a', 'b', 'a']
We want to group all the values onto an object as keys as the method of deduplication. So we use reduce with an object as the default value:
[].reduce(fn, {})
The next step is to create a reduce function which will put the values in the array onto the object. The end result is an object with a unique set of keys.
const reduced = data.reduce((l, r) => l[r] = l, {})
We set l[r] = l because in javascript the value of the assignment expression is returned when an assignment statement is used as an expression. l is the accumulator object and r is the key value. You can also use Object.assign(l, { [r]: (l[r] || 0) + 1 }) or something similar to get the count of each value if that was important to you.
Next we want to get the keys of that object
const keys = Object.keys(reduced)
Then simply use the built-in sort
console.log(keys.sort())
Which is the set of unique values of the original array, sorted
['a', 'b']
The solution in a more elegant way.
var myData=['237','124','255','124','366','255'];
console.log(Array.from(new Set(myData)).sort((a,b) => a - b));
I know the question is very old, but maybe someone will come in handy
A way to use a custom sort function
//func has to return 0 in the case in which they are equal
sort_unique = function(arr,func) {
func = func || function (a, b) {
return a*1 - b*1;
};
arr = arr.sort(func);
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (func(arr[i-1],arr[i]) != 0)
ret.push(arr[i]);
}
}
return ret;
}
Example: desc order for an array of objects
MyArray = sort_unique(MyArray , function(a,b){
return b.iterator_internal*1 - a.iterator_internal*1;
});
No redundant "return" array, no ECMA5 built-ins (I'm pretty sure!) and simple to read.
function removeDuplicates(target_array) {
target_array.sort();
var i = 0;
while(i < target_array.length) {
if(target_array[i] === target_array[i+1]) {
target_array.splice(i+1,1);
}
else {
i += 1;
}
}
return target_array;
}
I guess I'll post this answer for some variety. This technique for purging duplicates is something I picked up on for a project in Flash I'm currently working on about a month or so ago.
What you do is make an object and fill it with both a key and a value utilizing each array item. Since duplicate keys are discarded, duplicates are removed.
var nums = [1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 10];
var newNums = purgeArray(nums);
function purgeArray(ar)
{
var obj = {};
var temp = [];
for(var i=0;i<ar.length;i++)
{
obj[ar[i]] = ar[i];
}
for (var item in obj)
{
temp.push(obj[item]);
}
return temp;
}
There's already 5 other answers, so I don't see a need to post a sorting function.
// Another way, that does not rearrange the original Array
// and spends a little less time handling duplicates.
function uniqueSort(arr, sortby){
var A1= arr.slice();
A1= typeof sortby== 'function'? A1.sort(sortby): A1.sort();
var last= A1.shift(), next, A2= [last];
while(A1.length){
next= A1.shift();
while(next=== last) next= A1.shift();
if(next!=undefined){
A2[A2.length]= next;
last= next;
}
}
return A2;
}
var myData= ['237','124','255','124','366','255','100','1000'];
uniqueSort(myData,function(a,b){return a-b})
// the ordinary sort() returns the same array as the number sort here,
// but some strings of digits do not sort so nicely numerical.
function sort() only is only good if your number has same digit, example:
var myData = ["3","11","1","2"]
will return;
var myData = ["1","11","2","3"]
and here improvement for function from mrmonkington
myData.sort().sort(function(a,b){return a - b;}).filter(function(el,i,a){if(i==a.indexOf(el) & el.length>0)return 1;return 0;})
the above function will also delete empty array and you can checkout the demo below
http://jsbin.com/ahojip/2/edit
O[N^2] solutions are bad, especially when the data is already sorted, there is no need to do two nested loops for removing duplicates. One loop and comparing to the previous element will work great.
A simple solution with O[] of sort() would suffice. My solution is:
function sortUnique(arr, compareFunction) {
let sorted = arr.sort(compareFunction);
let result = sorted.filter(compareFunction
? function(val, i, a) { return (i == 0 || compareFunction(a[i-1], val) != 0); }
: function(val, i, a) { return (i == 0 || a[i-1] !== val); }
);
return result;
}
BTW, can do something like this to have Array.sortUnique() method:
Array.prototype.sortUnique = function(compareFunction) {return sortUnique(this, compareFunction); }
Furthermore, sort() could be modified to remove second element if compare() function returns 0 (equal elements), though that code can become messy (need to revise loop boundaries in the flight). Besides, I stay away from making my own sort() functions in interpreted languages, since it will most certainly degrade the performance. So this addition is for the ECMA 2019+ consideration.
The fastest and simpleness way to do this task.
const N = Math.pow(8, 8)
let data = Array.from({length: N}, () => Math.floor(Math.random() * N))
let newData = {}
let len = data.length
// the magic
while (len--) {
newData[data[len]] = true
}
var array = [2,5,4,2,5,9,4,2,6,9,0,5,4,7,8];
var unique_array = [...new Set(array)]; // [ 2, 5, 4, 9, 6, 0, 7, 8 ]
var uniqueWithSorted = unique_array.sort();
console.log(uniqueWithSorted);
output = [ 0, 2, 4, 5, 6, 7, 8, 9 ]
Here, we used only Set for removing duplicity from the array and then used sort for sorting array in ascending order.
I'm afraid you can't combine these functions, ie. you gotta do something like this:-
myData.unique().sort();
Alternatively you can implement a kind of sortedset (as available in other languages) - which carries both the notion of sorting and removing duplicates, as you require.
Hope this helps.
References:-
Array.sort
Array.unique

How do I empty an array in JavaScript?

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is there a way to empty an array and if so possibly with .remove()?
For instance,
A = [1,2,3,4];
How can I empty that?
Ways to clear an existing array A:
Method 1
(this was my original answer to the question)
A = [];
This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.
This is also the fastest solution.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
Method 2 (as suggested by Matthew Crumley)
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.
Method 3 (as suggested by Anthony)
A.splice(0,A.length)
Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
Method 4 (as suggested by tanguy_k)
while(A.length > 0) {
A.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
Performance
Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.
As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.
The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).
This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
A.length = 0;
Here the fastest working implementation while keeping the same array ("mutable"):
function clearArray(array) {
while (array.length > 0) {
array.pop();
}
}
FYI it cannot be simplified to while (array.pop()): the tests will fail.
FYI Map and Set define clear(), it would have seem logical to have clear() for Array too.
TypeScript version:
function clearArray<T>(array: T[]) {
while (array.length > 0) {
array.pop();
}
}
The corresponding tests:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152
jsPerf offline. Similar benchmark: https://jsben.ch/hyj65
A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:
A.splice(0, A.length);
The answers that have no less that 2739 upvotes by now are misleading and incorrect.
The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].
Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.
This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.
Let's say your mother asks you to empty the trash can.
You don't bring in a new one as if you've done what you've been asked for.
Instead, you empty the trash can.
You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];
Emptying an array object is the easiest thing ever:
A.length = 0;
This way, the can under "A" is not only empty, but also as clean as new!
Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:
while(A.length > 0) {
A.pop();
}
Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:
A.splice(0, A.length);
No, you were asked to empty it:
A.length = 0;
This is the only code that correctly empties the contents of a given JavaScript array.
Performance test:
http://jsperf.com/array-clear-methods/3
a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length) // 97% slower
while (a.length > 0) {
a.pop();
} // Fastest
You can add this to your JavaScript file to allow your arrays to be "cleared":
Array.prototype.clear = function() {
this.splice(0, this.length);
};
Then you can use it like this:
var list = [1, 2, 3];
list.clear();
Or if you want to be sure you don't destroy something:
if (!Array.prototype.clear) {
Array.prototype.clear = function() {
this.splice(0, this.length);
};
}
Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.
You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse.
Imagine you have this array:
var arr = [1, 2, 3, 4, 5]; //the array
OK, just simply run this:
arr.length = 0; //change the length
and the result is:
[] //result
easy way to empty an array...
Also using loop which is not necessary but just another way to do that:
/* could be arr.pop() or arr.splice(0)
don't need to return as main array get changed */
function remove(arr) {
while(arr.length) {
arr.shift();
}
}
There are also tricky way which you can think about, for example something like this:
arr.splice(0, arr.length); //[]
So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array.
Also other ways like simply reassign the array for example:
arr = []; //[]
If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length.
As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like:
Array.prototype.remove = Array.prototype.remove || function() {
this.splice(0, this.length);
};
and you can simply call it like this to empty any array in your javascript application:
arr.remove(); //[]
If you are using
a = [];
Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.
For ex.
var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];
or
a.length = 0;
When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.
Instead of these two solutions are better.
a.splice(0,a.length)
and
while(a.length > 0) {
a.pop();
}
As per previous answer by kenshou.html, second method is faster.
There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(Math.random());
}
for (var j = 0; j < 1000; j++) {
while (arr.length > 0) {
arr.pop(); // this executes 100 times, not 100000
}
}
I have created a new test that works correctly :
http://jsperf.com/empty-javascript-array-redux
Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).
Array.prototype.clear = function() {
this.length = 0;
};
And call it: array.clear();
In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in #tanguy_k's answer above.
(for an intro to the aforementioned tab you can check out here)
Stackoverflow forces me to copy the jsfiddle so here it is:
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]="something"
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.
Use a modified version of Jan's initial suggestion:
var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
A.pop();
}
Terser:
for (let i = A.length; i > 0;A.pop(),i--) {}
Or here's another take:
while(!A[Symbol.iterator]().next().done)A.shift()
A.splice(0);
I just did this on some code I am working on. It cleared the array.
If you use constants then you have no choice:
const numbers = [1, 2, 3]
You can not reasign:
numbers = []
You can only truncate:
numbers.length = 0
To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'
length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
pop() : The pop method removes the last element from an array and returns that returns the removed value.
shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
Example:
var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]
var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];
var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);
refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);
mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);
mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);
Array.prototype.poptill_length = function (e) {
while (this.length) {
if( this.length == e ) break;
console.log('removed last element:', this.pop());
}
};
new Array() | [] Create an Array with new memory location by using Array constructor or array literal.
mainArr = []; // a new empty array is addressed to mainArr.
var arr = new Array('10'); // Array constructor
arr.unshift('1'); // add to the front
arr.push('15'); // add to the end
console.log("After Adding : ", arr); // ["1", "10", "15"]
arr.pop(); // remove from the end
arr.shift(); // remove from the front
console.log("After Removing : ", arr); // ["10"]
var arrLit = ['14', '17'];
console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
function indexedItem( arr ) {
var indexedStr = "";
arr.forEach(function(item, index, array) {
indexedStr += "{"+index+","+item+"}";
console.log(item, index);
});
return indexedStr;
}
slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.
var shallowCopy = mainArr.slice(); // this is how to make a copy
var cloneArr = mainArr.slice(0, 3);
console.log('Main', mainArr, '\tCloned', cloneArr);
cloneArr.length = 0; // Clears current memory location of an array.
console.log('Main', mainArr, '\tCloned', cloneArr);
I'm surprised no one has suggested this yet:
let xs = [1,2,3,4];
for (let i in xs)
delete xs[i];
This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied':
xs
=> Array [ <4 empty slots> ]
[...xs]
=> Array [ undefined, undefined, undefined, undefined ]
xs.length
=> 4
xs[0]
=> ReferenceError: reference to undefined property xs[0]
You can produce an equivalent array with [,,,,] or Array(4)

Categories

Resources