简体   繁体   中英

lodash - filter collection by nested items count

Is there any simple solution (vanilla js or lodash) to filter collection by nested items count?

For example there is following grouped collection:

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

If I need to take 2 items it should return:

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

If I need to take 5 items it should return:

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

You need to iterate the items (for...of in this case), and count the number of items in the result + the current object items length.

If it's less or equal to the total wanted ( n ) you push the original object. If it's more, you slice the nested array, so it will include the difference.

If the current count is equal or more than n (or if the loop ends) return the result ( 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'))

My solution, maybe not perfect but it works :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM