Home >Web Front-end >JS Tutorial >JavaScript uses Array filter() to compress sparse arrays

JavaScript uses Array filter() to compress sparse arrays

小云云
小云云Original
2018-02-26 09:02:082143browse

What is a sparse array

The indexes of array elements do not have to be consecutive, there can be gaps between them. Every javaScript array has a length property. For non-sparse arrays, this property is the number of array elements; for sparse arrays, length is greater than the number of all elements.

The Array filter() method skips missing elements in a sparse array, and its return array is always dense. This article introduces you to the relevant knowledge of using the Array filter() method to compress sparse arrays in JavaScript. Friends who need it can refer to it. I hope it can help you.

(1) Compress the vacancies of the sparse array:


var dense = sparse.filter( function(currentValue)
{ 
return true; 
}
);

(2) Compress the vacancies of the sparse array, and delete undefined and null elements:


var dense = sparse.filter( function(currentValue) 
{ 
return currentValue !== undefined && currentValue!= null;
} 
)

Related recommendations:

php function array_filter() that uses a callback function to filter elements in an array

Detailed explanation of usage examples of find() and filter() operations in jQuery

Detailed explanation of usage of filter() method to traverse DOM nodes

The above is the detailed content of JavaScript uses Array filter() to compress sparse arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn