【问题标题】:Get values of array based on binary string根据二进制字符串获取数组的值
【发布时间】:2022-07-20 23:03:33
【问题描述】:
fruits = ["apple", "orange", "banana", "grape"]

dataBinary = "1010";

因为它是索引02 中的1 dataBinary,所以我的水果应该是

myFruits = ["apple", "banana"]

最快的方法是什么(性能方面)?因为我必须用不同的dataBinary 多次运行它,而且水果的长度要长得多

我的尝试

  for (let i = 0; i < dataBinary.length; i++) {
    const j = parseInt(dataBinary[i]);

    if (j)
      if (data.colors.includes(colors[i])) {
        myFruits.push(id);
        break;
      }
  }

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你可以用filter一行完成所有操作:

    const fruits = ["apple", "orange", "banana", "grape"]
    
    const dataBinary = "1010";
    
    const myFruits = fruits.filter((fruit, i) => dataBinary[i] === "1");
    
    console.log(myFruits);

    您只想保留 dataBinary 中各自索引等于 1 的水果。

    我不知道data.colors 位是怎么回事,但您也可以使用&amp;&amp; (AND) 运算符添加这一点,以仅获取符合这两个条件的水果:

    const myFruits = fruits.filter((fruit, i) => dataBinary[i] === "1" && data.colors.includes(colors[i]));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 2021-11-09
      • 1970-01-01
      • 2014-04-28
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多