【问题标题】:Comparing array (start with option) by giving another array in JavaScript通过在 JavaScript 中给出另一个数组来比较数组(从选项开始)
【发布时间】:2019-12-11 06:17:22
【问题描述】:

我有两个数组;selectedFunctionarray1。用这些值

['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001']

allFunctionsarray2。使用这些值;

[ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]

如果数组 1 中的元素数组 2 中的给定元素开始,则将数组 1 的该元素推入 myFinalSelectedFunctions[]array3。在上述数组中,array1 的第 2 和第 3 个元素应该被推入 array3。如何在 javascript/Nodejs 中执行此类任务?我有javascript的基本知识,不是专家。

【问题讨论】:

  • 您可以遍历这两个数组并找到匹配项。

标签: javascript arrays node.js


【解决方案1】:

如果 array1 中的十六进制代码 .startsWith() array2 中的十六进制代码,您可以使用 .filter().some() 返回 true:

const array1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const array2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ];

const res = array1.filter(hex => array2.some(code => hex.startsWith(code)));
console.log(res);

【讨论】:

  • 如果我想做与上述要求相反的事情......意味着'如果不开始'......那么如何执行这样的任务......
  • @AmirAli 如果我正确理解您的要求,我相信您会想将array2.some(code => hex.startsWith(code)) 更改为array2.every(code => !hex.startsWith(code))
  • 是的,你是对的,我也试过这个......它有效......再次感谢......您的及时回复......
【解决方案2】:

你可以做到以下几点:

const arr1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const arr2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]

const arr3 = [];

for (let i = 0; i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
    if (arr1[i].startsWith(arr2[j])) {
      arr3.push(arr1[i])
    }
  }
}

console.log(arr3)

@nick-parsons 的回答更简洁。你可以去。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多