【问题标题】:reduce array of objects into nested arrays将对象数组减少为嵌套数组
【发布时间】:2019-05-02 10:15:56
【问题描述】:

我正在尝试将元素相互嵌套,但今天我脑子里放了个屁。

如果数组中的一个元素是isParent: true,那么它将在exist数组中创建一个新数组,并且所有后续元素都将嵌套在该数组中。

这是我迄今为止尝试过的:

//input [{},{},{},{isParent}, {}, {}, {isParent}, {}, {}]
//desired output [{}, {}, {}, [{}, {}, {}, [{}, {}, {}]]]

var nestInParent = elements => {
      let ignoreIndexAfter = null;
      return elements.reduce((acc, { component, isParent }, index) => {
        if (isParent) {
          let remaining = elements.slice(index + 1);
   			ignoreIndexAfter = index;
          if (remaining.length > 0) {
            return [...acc, [component, ...nestInParent(remaining)]];
          } else {
            return [...acc, [component]];
          }
        } else {
			if(ignoreIndexAfter === null || index < ignoreIndexAfter){
               return [...acc, component];
            }
return acc;
        }
      }, []);
    };
const isParent = true;
const input = [
  {component:0},
  {component:1},
  {component:2},
  {isParent, component:3},
  {component:4},
  {component:5},
  {isParent, component:6},
  {component:7},
  {component:8}
];
const expected = [
  0,
  1,
  2,
  [
    3,
    4,
    5,
    [
      6,
      7,
      8
    ]
  ]
];
const output = nestInParent(input);
console.log("input:", input);
console.log("output:", output);
console.log("passes?", JSON.stringify(output) === JSON.stringify(expected));
.as-console-wrapper { max-height: 100% !important; }

【问题讨论】:

  • if(t &gt; startLen) return acc; 应该做什么?
  • 我编辑了代码,它不再存在。它工作得更好一点,但并不完全。
  • 主要问题是你遍历整个数组的每一个递归步骤。这是浪费时间,并且使事情变得过于复杂。如果不合适,请勿使用 reduce。

标签: javascript arrays logic


【解决方案1】:

您也可以使用reduce 方法和一个变量来跟踪是否找到带有isParent 属性的元素。

const isParent = true;
const input = [{component:0},{component:1},{component:2},{isParent, component:3},{component:4},{component:5},{isParent, component:6},{component:7},{component:8}];

function nest(data) {
  let nested = false;
  return data.reduce((r, e, i) => {
    if(!nested) {
    	if(e.isParent) {
      	const res = nest(data.slice(i + 1))
        r.push([e.component, ...res])
        nested = true;
      } else {
        r.push(e.component)
      }
    }
    return r;
  }, [])
}

const result = nest(input);
console.log(result)

你也可以这样写。

const isParent = true;
const input = [{ component: 0 }, { component: 1 }, { component: 2 }, { isParent, component: 3 }, { component: 4 }, { component: 5 },{ isParent, component: 6 }, { component: 7 }, { component: 8 }];

function nest(data, nested) {
  return data.reduce((r, e, i) => {
    if(!nested) {
      if(e.isParent && i != 0) {
        r.push(nest(data.slice(i)))
        nested = true;
      } else {
        r.push(e.component)
      }
    }
    return r;
  }, [])
}

const result = nest(input);
console.log(result)

【讨论】:

    【解决方案2】:

    我会说您的代码失败是因为它过于复杂。你只需要:

    const result = [];
    let current = result;
    
     for(const { component, isParent } of data) {
       if(isParent) {
         current.push(current = [component]);
       } else current.push(component);
     }
    

    const input = [
      {component:0},
      {component:1},
      {component:2},
      {isParent: true, component:3},
      {component:4},
      {component:5},
      {isParent: true, component:6},
      {component:7},
      {component:8}
    ];
    
    const result = [];
    let current = result;
    
     for(const { component, isParent } of input) {
       if(isParent) {
         current.push(current = [component]);
       } else current.push(component);
     }
    
    console.log(result);

    或者如果你真的想减少,reduceRight:

    const result = data.reduceRight((acc, { isParent, component }) => isParent ? [[component, ...acc]] : [component, ...acc], []);
    

    const input = [
      {component:0},
      {component:1},
      {component:2},
      {isParent: true, component:3},
      {component:4},
      {component:5},
      {isParent: true, component:6},
      {component:7},
      {component:8}
    ];
    
    const result = input.reduceRight((acc, { isParent, component }) =>
    isParent ? [[component, ...acc]] : [component, ...acc], []);
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2019-10-16
      • 2017-08-17
      相关资源
      最近更新 更多