curious1
curious1

Reputation: 14717

The efficient way to eliminate some elements in a large array

I need to have an efficient to clean up a large (about 5000 elements). It consists of numbers and other types of data.

var arr = [2, "da", 3, "", dd, 4];

I need to have an array with only numbers. So far this is what I have (a test and copy method).

    var newArr = [];
    var index = 0;
    for (var k=0; k<arr.length;k++) {
        var ele = arr[k];
        if (!isNaN(parseFloat(ele)) && isFinite(ele)) {
            newArr[index++] = ele;
        } 
    }
    return newArr;

Upvotes: 1

Views: 61

Answers (2)

Alexandre Nicolas
Alexandre Nicolas

Reputation: 1949

This should be efficient.

var newArr = arr.slice(); // copy the array, this is optionnal depending of the context
for (var k=arr.length - 1; k >= 0; k--) {
    if (isNaN(arr[k]) || !isFinite(arr[k])) {
        newArr.splice(k, 1); // replace by arr if you don't copy the array
    } 
}
return newArr;

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use Array.prototype.filter() function:

var arr = [2, "da", 3, "", 'dd', 4, -4],
    newArr = arr.filter(function (v) {
        return Number(v) && isFinite(v);
    });

console.log(newArr);

Upvotes: 1

Related Questions