Q:

Splice array of objects by max-length

There's an array of objects like
var a =[
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}]

How to slice/splice/filter this array to make it return say first 3 items of type t1 and first 4 items of t2?

A:

You can use filter() and then slice(). Pass 0 and number of items to slice() as parameters

var a =[
{type: 't1', value: 'x1'},
{type: 't1', value: 'x2'},
{type: 't1', value: 'x3'},
{type: 't1', value: 'x4'},
{type: 't2', value: 'x5'},
{type: 't2', value: 'x1'},
{type: 't2', value: 'x2'},
{type: 't2', value: 'x3'},
{type: 't2', value: 'x4'},
{type: 't2', value: 'x5'}]

function items(type,num){
  return a.filter(x => x.type === type).slice(0,num);
}

console.log(items('t1',3));
console.log(items('t2',4));

A:

Use filter followed by slice:

const a = [
  {type: 't1', value: 'x1'},
  {type: 't1', value: 'x2'},
  {type: 't1', value: 'x3'},
  {type: 't1', value: 'x4'},
  {type: 't2', value: 'x5'},
  {type: 't2', value: 'x1'},
  {type: 't2', value: 'x2'},
  {type: 't2', value: 'x3'},
  {type: 't2', value: 'x4'},
  {type: 't2', value: 'x5'}
];

const t1 = a.filter(x => x.type === 't1').slice(0, 3);
const t2 = a.filter(x => x.type === 't2').slice(0, 4);

console.log(t1);
console.log(t2);

Or use reduce:

const a = [
  {type: 't1', value: 'x1'},
  {type: 't1', value: 'x2'},
  {type: 't1', value: 'x3'},
  {type: 't1', value: 'x4'},
  {type: 't2', value: 'x5'},
  {type: 't2', value: 'x1'},
  {type: 't2', value: 'x2'},
  {type: 't2', value: 'x3'},
  {type: 't2', value: 'x4'},
  {type: 't2', value: 'x5'}
];

const getByType = (arr, prop, num) =>
  arr.reduce(([out, i], x) => (match = x.type === prop, [
    match && i < num ? [...out, x] : out,
    match ? i + 1 : i
  ]),
  [[], 0])[0];

console.log(getByType(a, 't1', 3));
console.log(getByType(a, 't2', 4));

