【问题标题】:Javascript array filter child! [closed]Javascript数组过滤子![关闭]
【发布时间】:2019-08-10 03:12:58
【问题描述】:

第一个数组如下:

   var arr = [
  {
    key: 1,
    title: 'aa',
    children: [
      {
        key: 2,
        title: 'bb',
        children: [
          {
            key: 3,
            title: 'cc', 
            children: [
              {
                key: 5,
                title: 'ee', 
                children: [
                  {
                    key: 6,
                    title: 'ff'
                  },
                  {
                    key: 7,
                    title: 'gg'
                  },
                  {
                    key: 8,
                    title: 'hh'
                  }                  
                ]
              }
            ]
          },
          {
            key: 4,
            title: 'dd', 
          }          
        ]
      }    
    ]
  }
]
console.log(arr)

如果第二个数组如下:

arr2 = [1, 2, 3, 4, 8]

那么我希望数组3如下:

arr3 = [4, 8]

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour(你会得到一个徽章!),环顾四周,并阅读help center,尤其是How do I ask a good question? 我还推荐Jon Skeet 的Writing the Perfect Question
  • 好的,所以你的前两个例子是有道理的,但是你开始谈论 If is the second array, then I expect the final array to be as follows 这完全让我失去了。您能否详细说明这一点以及您期望如何获得arr3
  • @T.J.Crowder 喜欢您获得徽章! 了解人们进行巡回演出的好方法。 +1
  • @kemicofa - :-) 这确实意味着我每次都必须点击几下以确保他们还没有它,但我认为这是值得的。
  • 请详细说明。我们不明白你想要什么。

标签: javascript node.js


【解决方案1】:

你可以先获取路径,然后过滤给定的key,如果超过两个路径,则过滤掉这个值。

function filter(source, targets) {

    function getPath(array, target) {
        return array.reduce((r, { key, children }) => {
            var temp;
            if (key === target) return r.concat(key);
            if (children) {
                temp = getPath(children, target);
                if (temp.length) return r.concat(key, temp);
            }
            return r;
        }, [])
    }

    var temp = targets.map(k => getPath(source, k));
    return targets.filter(v => !temp.some((c => a => a.includes(v) && ++c)(-1)));
}

var array = [{ key: 1, title: 'aa', children: [{ key: 2, title: 'bb', children: [{ key: 3, title: 'cc', children: [{ key: 5, title: 'ee', children: [{ key: 6, title: 'ff' }, { key: 7, title: 'gg' }, { key: 8, title: 'hh' }] }] }, { key: 4, title: 'dd', }] }] }],
    result = filter(array, [1, 2, 3, 4, 8]);

console.log(result);

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 2022-07-13
    • 1970-01-01
    • 2022-01-09
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多