You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中按值类型过滤数组有没有更优的实现方法?

按数组元素类型过滤的实现优化

你的现有实现是完全可行的,对于仅需要区分基础类型(数字、字符串、布尔值等)的场景已经能正常工作,以下是几个可以优化的方向:

  • 减少数组遍历次数
    你现在调用了两次filter,会把整个数组遍历两遍,如果数组数据量较大,可以改成一次遍历同时收集两种类型的结果,性能更好:
const list = ["lorem1",  "lorem2", "lorem3" , "lorem4", 1 ,2 ,3]
const targetType = typeof 1
const numbers = []
const words = []
list.forEach(item => {
  typeof item === targetType ? numbers.push(item) : words.push(item)
})
console.log(numbers) // [1,2,3]
console.log(words) // ["lorem1","lorem2","lorem3","lorem4"]
  • 解决typeof的判断盲区
    typeof对于部分特殊值的判断有不符合预期的表现,比如typeof null返回'object'、typeof []也返回'object',如果后续你需要更精准的类型判断(比如要区分数组、普通对象、null、日期等),可以替换成Object.prototype.toString.call()来判断:
// 精准获取类型的工具函数
const getExactType = (val) => Object.prototype.toString.call(val).slice(8, -1).toLowerCase()

// 使用示例
const mixedList = [1, 'a', null, {}, [], new Date(), false]
const filterByType = (arr, targetType) => {
  const matched = []
  const unmatched = []
  arr.forEach(item => {
    getExactType(item) === targetType ? matched.push(item) : unmatched.push(item)
  })
  return { matched, unmatched }
}

const { matched: numbers, unmatched: others } = filterByType(mixedList, 'number')
console.log(numbers) // [1]
  • 封装为通用工具函数
    如果需要频繁做这类过滤,可以把逻辑封装成可复用的函数,传入数组和要匹配的类型就能直接返回两类结果,不用每次都重复写过滤逻辑。

内容的提问来源于stack exchange,提问作者Yago Quintino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:06:03