How to filter an array in javascript?

前端 未结 7 1671
清酒与你
清酒与你 2020-11-28 16:38

This is an array,

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

7条回答
  •  情话喂你
    2020-11-28 17:10

    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

提交回复
热议问题