SOURCE

// 定义一个 Query 类
class Query {
  constructor(data) {
    this.data = data;
  }

  where(callback) {
    this.data = this.data.filter(callback);
    return this; // 返回 this 以实现链式调用
  }

  sortBy(key) {
    this.data.sort((a, b) => a[key] - b[key]);
    return this;
  }

  groupBy(key) {
    const groups = {};
    this.data.forEach(item => {
      const value = item[key];
      if (!groups[value]) {
        groups[value] = [];
      }
      groups[value].push(item);
    });
    this.data = groups;
    return this;
  }

  execute() {
    return this.data;
  }
}
const list =[{
    age:19,
    id:2,
    name:'cc'
},
{
    age:19,
    id:3,
    name:'cc'
},
{
    age:121,
    id:1,
    name:'bc'
},
{
    age:121,
    id:1,
    name:'ac'
}
]
const result = new Query(list)
  .where(item => item.age > 18)
  .sortBy('id')
  .groupBy('name')
  .execute();

console.log(result);
console 命令行工具 X clear

                    
>
console