How to filter an array in javascript?

前端 未结 7 1659
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    2020-11-28 17:15

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

提交回复
热议问题