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