How to filter an array in javascript?

This is an array,

total = ["10%", 1000, "5%", 2000] . how can i filter these into two array like, percentage = ["10%","5%"] and absolute = [1000,2000] using javascript array filter.


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:

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);
});