locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
15 lines (14 loc) • 566 B
JavaScript
export function compact(arr) {
// parity verified: Ruby 3.3
// discuss at: https://locutus.io/ruby/Array/compact/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns a new array with all nil (null/undefined) values removed.
// example 1: compact(['a', null, 'b', undefined, 'c'])
// returns 1: ['a', 'b', 'c']
// example 2: compact([1, 2, 3])
// returns 2: [1, 2, 3]
if (!Array.isArray(arr)) {
return [];
}
return arr.filter((item) => item != null);
}