javascript - 选择表数据(对象数组)JS的高性能方法

标签 javascript arrays mapreduce

我正在尝试优化从大表(对象数组)中选择数据。

我想从一行中保存多个值,然后写入 localStorage。

let customerTable = [
  {
    "customer": "Apple Computers",
    "contact": "Steve Jobs",
    "id": 1,
    "city": "Cupertino"
  },
  {
    "customer": "Microsoft",
    "contact": "Bill Gates",
    "id": 2,
    "city": "Redmond"
  },
  {
    "customer": "Microsoft",
    "contact": "Satya Nadella",
    "id": 3,
    "city": "Redmond"
  }
]

let selectedRow = customerTable
  .filter(i => { return i.customer === selectedCustomer })
  .filter(i => { return i.contact === selectedContact })

let id = selectedRow
  .map(a => a.id)                                                  
  .filter((item, pos, self) => {return self.indexOf(item) === pos}) // Remove duplicates

let city = selectedRow
  .map(a => a.city)
  .filter((item, pos, self) => { return self.indexOf(item) === pos })

是否有更高效的方法从这种类型的数据模型中选择多个值?

最佳答案

过滤器看起来不错;但是你可以filter with composing functions .

获取唯一值可以使用 Set 进行优化和 reduce :

let id = [...selectedRow.reduce(
  (result,item)=>result.add(item.id)
  ,new Set()
)]

或者正如 Jonas 指出的那样(所以你不需要 reduce):

let id = [...new Set(
  selectedRow.map(item=>item.id)
)]

关于javascript - 选择表数据(对象数组)JS的高性能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56599058/

相关文章:

javascript - 包含图像的 div 的 scrollHeight 值

javascript - Typescript/Angular 中的动态谷歌可视化

java - 在哪里可以看到从 hadoop pig 语句生成的 mapreduce 代码

JavaScript——函数基础

javascript - document.getElementById 有效,但 document.getElementsByTagName 无效

php - 如何在以下代码中将两个查询放入一个数组中?

php - array_walk vs array_map vs foreach

arrays - 向量化访问非连续内存位置的循环

hadoop - 在reduce任务中调用htable.get(rowID)对于随机行返回NULL

hadoop - 自定义分区程序 : N number of keys to N different files