繁体   English   中英

拆分二维数组

[英]Splitting a 2-Dimensional Array

我有这个二维任务数组

const graph = [
    ['tie your shoes', 'put on your shoes'],
    ['put on your jacket', 'put on your shirt'],
    ['put on your shoes', 'put on your shorts'],
    ['put on your jacket', 'put on your shorts'],
    ['buy eggs from store', 'cook eggs'],
    ['heat up skillet', 'cook eggs']
]

如果它们彼此没有关联,我需要将此图拆分为两个单独的 arrays。 (即,穿鞋和煮鸡蛋在图中没有关联/关系)

graph中的每个数组都是任务的关联。 如果两个任务可以追溯到一个共同的任务,则可以在两个任务之间找到关联 - 穿上夹克可以追溯到穿袜子

结果应该是这样的

const graph_1 = [
    ['tie your shoes', 'put on your shoes'],
    ['put on your jacket', 'put on your shirt'],
    ['put on your shoes', 'put on your shorts'],
    ['put on your jacket', 'put on your shorts']
]

const graph_2 = [
    ['buy eggs from store', 'cook eggs'],
    ['cook eggs', 'heat up skillet']
]

我现在不担心对它们进行分类 - 只关心将它们分开

您可以使用循环组合来检查包含关键字的数组。

 const graph = [ ['tie your shoes', 'put on your shoes'], ['put on your jacket', 'put on your shirt'], ['put on your shoes', 'put on your shorts'], ['put on your jacket', 'put on your shorts'], ['buy eggs from store', 'cook eggs'], ['heat up skillet', 'cook eggs'] ] // Keywords const clothes = ['shoes', 'jacket', 'shorts'] const foods = ['eggs', 'heat', 'skillet'] // Creating graph 1 const graph_1 = graph.filter(array => { return array.reduce((arr, str) => { clothes.forEach(item => { if (str.includes(item)) { arr.push(str) } }) return arr }, []).length }) // Creating graph 2 const graph_2 = graph.filter(array => { return array.reduce((arr, str) => { foods.forEach(item => { if (str.includes(item)) { arr.push(str) } }) return arr }, []).length }) console.log(graph_1) console.log(graph_2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM