【问题标题】:lodash - filter collection by nested items countlodash - 按嵌套项计数过滤集合
【发布时间】:2021-02-21 17:24:04
【问题描述】:

有没有简单的解决方案(vanilla js 或 lodash)按嵌套项计数过滤集合?

例如有以下分组集合:

[
  {
    Items: ['a', 'b', 'c'],
    Name: 'Group 1'
  },
  {
    Items: ['d', 'e','f'],
    Name: 'Group 2'
  }
]

如果我需要带 2 件物品,它应该返回:

[
  {
    Items: ['a', 'b'],
    Name: 'Group 1'
  }
]

如果我需要带 5 件物品,它应该返回:

[
  {
    Items: ['a', 'b', 'c'],
    Name: 'Group 1'
  },
  {
    Items: ['d', 'e'],
    Name: 'Group 2'
  }
]

【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:

    您需要迭代项目(在本例中为 for...of),并计算结果中的项目数 + 当前对象项目长度。

    如果它小于或等于所需的总数 (n),则推送原始对象。如果更多,则对嵌套数组进行切片,因此它将包含差异。

    如果当前计数等于或大于n(或者如果循环结束)返回结果(res)。

    const fn = (arr, n, key) => {
      let count = 0
      const res = []
      
      for(const o of arr) {
        const len = o[key].length
        
        res.push(count + len <= n ? o : { ...o, [key]: o[key].slice(0, n - count) })
        
        count += len
      
        if(count >= n) return res
      }
      
      return res
    }
    
    const arr = [{"Items":["a","b","c"],"Name":"Group 1"},{"Items":["d","e","f"],"Name":"Group 2"}]
    
    console.log(fn(arr, 2, 'Items'))
    
    console.log(fn(arr, 5, 'Items'))
    
    console.log(fn(arr, 8, 'Items'))

    【讨论】:

    • 谢谢,刚刚想出了类似的解决方案 :)
    • 不客气 :) 我不会为此使用 Array.some。你可能想试试 lodash 的_.takeWhile()
    【解决方案2】:

    我的解决方案,也许并不完美,但它有效:)

    let array = [
      {
        Items: [
          'a',
          'b',
          'c'
        ],
        Name: 'Test1'
      },
      {
        Items: [
          'd',
          'e',
          'f'
        ],
        Name: 'Test2'
      }
    ];
    
    let itemsCount = 5;
    let filteredArray = [];
    
    array.some(group => {
      if (itemsCount <= 0) {
        return true;
      }
    
      if (group.Items.length <= itemsCount) {
        itemsCount -= group.Items.length;
      } else {
        group.Items = group.Items.slice(0, itemsCount);
        itemsCount = 0;
      }
    
      filteredArray.push(group);
    });
    
    console.log(filteredArray);
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2017-09-01
      • 1970-01-01
      相关资源
      最近更新 更多