【问题标题】:Function to return boolean when two indexes are present and order?当两个索引存在并排序时返回布尔值的函数?
【发布时间】:2020-07-11 01:53:03
【问题描述】:

如何编写一个函数回调,当订购 path 时将返回 boolean 匹配来自 source 数组的任意位置

我尝试过使用Array.prototype.includes,但没有成功。

注意

  1. source 数组将始终是 2 维的,并且没有更大的嵌套。
  2. 空值始终是一个数组。

const source = [
  ['source', 'nope'],
  ['source', 'id'],
  ['wow', 'source', 'id'],
  ['source', 'nope', 'id'],
  [],
  ['id', 'source'],
  ['id', 'source', 'id']
];


function cb(arr, path) {
  return true;
}

const ans = source.filter(i => cb(i, ['source', 'id']));

console.log(ans) 
// Correct Answer is:
// [['source', 'id'], ['wow', 'source', 'id'], ['id', 'source', 'id']]

【问题讨论】:

    标签: javascript arrays filtering


    【解决方案1】:

    我不确定这是否涵盖所有场景(如果. 是路径中的有效字符,则可能不会),或者即使它是一个很好的解决方案,但它确实会在您的评论中产生答案。只需将每个路径转换为. 分隔字符串,并将给定路径也作为. 分隔字符串查找。

    const source = [
      ['source', 'nope'],
      ['source', 'id'],
      ['wow', 'source', 'id'],
      ['source', 'nope', 'id'],
      [],
      ['id', 'source'],
      ['id', 'source', 'id']
    ];
    
    
    function cb(arr, path) {
      return arr.join('.').includes(path);
    }
    
    const ans = source.filter(i => cb(i, ['source', 'id'].join('.')));
    
    console.log(ans) 
    // Correct Answer is:
    // [['source', 'id'], ['wow', 'source', 'id'], ['id', 'source', 'id']]

    【讨论】:

    • 啊,这很聪明!这实际上适用于我的用例!
    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 2023-03-28
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多