有一系列类似的对象
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'}]
如何切片/拼接/过滤此数组以使其返回t1
类型的前3个项目和t2
类型的前4个项目?
答案 0 :(得分:3)
您可以先使用filter()
,然后再使用slice()
。将0
和项目数作为参数传递给slice()
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));
答案 1 :(得分:1)
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);
或使用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));
答案 2 :(得分:1)
这很粗糙。但是有效。
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'}];
let b = a.filter(x => x.type === 't1').slice(0,3).concat(a.filter(x => x.type === 't2').slice(0,4));
console.log(b);
答案 3 :(得分:1)
您可以使用创建一个对象的reduce
方法进行自定义功能,然后可以返回Object.values
。
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 sliceArr(arr, slice) {
const obj = arr.reduce((r, { type, ...rest }) => {
if(slice[type]) {
if(!r[type]) r[type] = [{ type, ...rest }];
else if(r[type].length < slice[type]) r[type].push({ type, ...rest })
}
return r;
}, {})
return [].concat(...Object.values(obj))
}
console.log(sliceArr(a, { t1: 3, t2: 4 }))