js数组统计问题?

存在一个二维数组
const a = [{mac: 11, children: [{mac: 2}]}, {mac: 12, children: [{mac: 3}]}]
如何快速统计出mac的所有取值并返回一个数组[11, 2, 12, 3]?,顺序没有要求,不使用解构语法

阅读 1.5k
2 个回答
const a = [{mac: 11, children: [{mac: 2}]}, {mac: 12, children: [{mac: 3}]}];

const macs = a.reduce((acc, curr) => {
  acc.push(curr.mac);
  curr.children.forEach(child => acc.push(child.mac));
  return acc;
}, []);

console.log(macs); // [11, 2, 12, 3]
type RecurMapResult<T> = [T, RecurMapResult<T>][]

function recurMap<T, R>(source: T[], next: (x: T) => T[], callbackfn: (x: T) => R): RecurMapResult<R> {
    return source.map(x => [callbackfn(x), recurMap(next(x), next, callbackfn)])
}
const a = [{ mac: 11, children: [{ mac: 2 }] }, { mac: 12, children: [{ mac: 3 }] }]

const result = recurMap(a, x => x.children as any ?? [], x => x.mac).flat(10)

console.log(result)

TS Playground

推荐问题
logo
Microsoft
子站问答
访问
宣传栏