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.

Answers:

Answer

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

Answer

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

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

Answer

you can do it using

let total = ["10%", 1000, "5%", 2000]


let result1 = total.filter(function(element){
    if(typeof element == "number"){
        return 1;
    }
    return 0;
})
let result2 = total.filter(function(element){
    if(typeof element == "string" && element.match(/\%$/)){
        return 1;
    }
    return 0;
})
console.log(result1, result2);

the first array filter all the number
the 2nd array filter elements which are a string and have a "%" in the end

Answer

use this code

$array = array('10%', '1000', '20%','2000');

//for show integer from array

print_r(array_filter($array, function ($var) { return (stripos($var, '%') === false); }));

//for show % array

print_r(array_filter($array, function ($var) { return (stripos($var, '%') == true); }));

Answer

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.