js如何筛出这个结果?

let arr = ['1_2', '682', '682_1', '682_2','912', '912_1']
  1. arr 中没有下划线 _ 的为父节点(比如 682912),有下划线的为子节点(比如 1_2912_1等),xxxxxx_1xxx_2 这类为父子关系(比如 682682_1682_2
  2. 筛父节点到 let fatherArr = [],筛子节点到let childrenArr = []
  3. 在有父节点的情况下,不筛子节点到 childrenArr

最终的结果示例

fatherArr = ['682', '912']
childrenArr = ['1_2']
阅读 1.9k
3 个回答

其实很简单的吖。使用 filterincludes 这俩API就可以了。

var sourceData = ['1_2', '682', '682_1', '682_2','912', '912_1']

var fatherArr = sourceData.filter(item=> !item.includes("_")) // 直接过滤掉包含 _ 的项
console.log(fatherArr)
// (2) ['682', '912']

var childrenArr = sourceData.filter(item => {
  // 如果当前项不包含 _ 则返回 false
  if(!item.includes("_")) return false
  // 解构赋值 当前项
  const [pid,cid] = item.split("_") // 使用 _ 拆分字符串为数组
  return !fatherArr.includes(pid) // 返回 取反的 fatherArr 是否包含pid的结果
})
console.log(childrenArr)
// ['1_2']

相关阅读

Array.prototype.filter() - JavaScript | MDN
Array.prototype.includes() - JavaScript | MDN
String.prototype.includes() - JavaScript | MDN
String.prototype.split() - JavaScript | MDN

const filter = (arr) => {
  const fatherArr = [];
  const childrenArr = [];

  arr.forEach((value) => {
    const isChildren = value.includes('_');
    if (!isChildren) {
      fatherArr.push(value);
    }
    const [parent] = value.split('_');
    if (!arr.includes(parent)) {
      childrenArr.push(value);
    }
  });

  return {
    fatherArr,
    childrenArr,
  };
};
let arr = ['1_2', '682', '682_1', '682_2','912', '912_1']
let fatherArr = arr.filter(v => !v.includes('_'))
let childrenArr = arr.filter(v => !fatherArr.includes(v.split('_')[0]))
推荐问题
宣传栏