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

Share:
10,184
Mukul Sharma
Author by

Mukul Sharma

Updated on June 04, 2022

Comments

  • Mukul Sharma
    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
      abhishekkannojia over 6 years
      Are the values will be in this order only ["percentage', 'absolute', ...] ?
    • trincot
      trincot over 6 years
      You really did not search? SO has many Q&A on such filters.
  • ViKiG
    ViKiG over 6 years
    You got the negation for filter condition in reverse.
  • alexmac
    alexmac over 6 years
    @vkgade what do you mean?
  • ViKiG
    ViKiG over 6 years
    The percents is the one which has '%' character , you negated the return value in percents instead of numbers.