How to filter an array in javascript?
10,184
Solution 1
You should use filter
method, which accepts a callback
function.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Also, use typeof
operator in order to find out the type of item from array. The typeof operator returns a string indicating the type of the unevaluated operand.
let total = ["10%", "1000", "5%", "2000"];
let percentage = total.filter(function(item){
return typeof item == 'string' && item.includes('%');
});
console.log(percentage);
let absolute = total.filter(function(item){
return typeof item == 'number' || !isNaN(item);
});
console.log(absolute);
Solution 2
let total = ["10%", 1000, "5%", 2000];
let percents = total.filter(item => item.toString().includes('%'));
let numbers = total.filter(item => !item.toString().includes('%'));
console.log(percents, numbers);
Solution 3
Make two arrays from one array by separating number and string using advance
js.
let total = ["10%", 1000, "5%", 2000];
var percentage = total.filter(e => isNaN(e));
var absolute = total.filter(e => !isNaN(e));
console.log({percentage , absolute});
Solution 4
You can use regular expressions since you have only strings in your array.
For % :
total.filter(function(element){
return /^[0-9]+\%$/gi.test(element);
});
For absolute :
total.filter(function(element){
return /^[0-9]+$/gi.test(element);
});
Solution 5
You can use Array#reduce to split the array:
const total = ["10%", 1000, "5%", 2000];
const { absolute, percentage } = total.reduce((arrs, item) => {
const key = typeof item === 'number' ? 'absolute' : 'percentage';
arrs[key].push(item);
return arrs;
}, { percentage: [], absolute: [] });
console.log(absolute);
console.log(percentage);
Author by
Mukul Sharma
Updated on June 04, 2022Comments
-
Mukul Sharma almost 2 years
This is an array:
total = ["10%", 1000, "5%", 2000]
How can I filter these into two arrays like:
percentage = ["10%","5%"] absolute = [1000,2000]
...using JavaScript array filter.
-
abhishekkannojia over 6 yearsAre the values will be in this order only ["percentage', 'absolute', ...] ?
-
trincot over 6 yearsYou really did not search? SO has many Q&A on such filters.
-
-
ViKiG over 6 yearsYou got the negation for filter condition in reverse.
-
alexmac over 6 years@vkgade what do you mean?
-
ViKiG over 6 yearsThe percents is the one which has '%' character , you negated the return value in percents instead of numbers.