【问题标题】:Javascript: no duplicate random string arrayJavascript:没有重复的随机字符串数组
【发布时间】:2018-05-03 03:59:19
【问题描述】:

我正在尝试从这个随机生成器数组中删除重复项。我尝试了许多可以删除重复项的不同代码行,但我无法让任何工作。

我用过的例子:

        filtered = idArray.filter(function (str) { return str.indexOf(idArray) === -1; });

代码:

     var idArray = ['img1', 'img2'];
        var newID=getRandomInt(2);
        var newCube=idArray[newID];
        document.getElementById(""+newCube+"").src="assets/button-yellow_x64.png";
        document.getElementById(""+newCube+"").src="assets/button-yellow_x64.png"; 

【问题讨论】:

标签: javascript arrays string random


【解决方案1】:

您可以在新的 ES6 中使用 Set,它将过滤多余的元素并将其类型转换为数组。

var idArray = ["img1", "img2", "img1", "img2"];
var distinctArray = [...new Set(idArray)];
console.log(distinctArray);

【讨论】:

    【解决方案2】:

    使用集合是较新且最好的答案,但如果您仍想实现您的要求,您可以使用对象哈希来跟踪项目,然后只获取键。例如:

    var idArray = ["img1", "img2", "img1", "img2"]
    var hash = {}
    idArray.forEach(id => hash[id] = true)
    var ids = Object.keys(hash)
    console.log(ids)

    【讨论】:

      【解决方案3】:

      要删除双打,您可以执行以下操作:

      //remove doubles from an array of primitive values
      console.log(
        "no doubles primitive values",
        [1,2,3,4,3,4,5,6,7,7,7,8,9,1,2,3,4].filter(
          (value,index,all)=>all.indexOf(value)===index
        )
      );
      //remove doubles from an array of references you can do the same thing
      const one = {id:1}, two = {id:2}, three = {id:3};
      console.log(
        "no doubles array of references",
        [one,two,one,two,two,one,three,two,one].filter(
          (value,index,all)=>all.indexOf(value)===index
        )
      );
      //remove doubles from an array of things that don't have the same reference
      //  but have same values (say id)
      console.log(
        "no doubles array of things that have id's",
        [{id:1},{id:1},{id:1},{id:2},{id:3},{id:2}].reduce(
          ([all,ids],item,index)=>
            [ all.concat(item), ids.concat(item.id) ],
          [[],[]]
        ).reduce(
          (all,ids)=>
            all.filter(
              (val,index)=>ids.indexOf(val.id)===index
            )
        )
      );

      或者你可以只创建一个不带双打的洗牌数组:

      const shuffle = arr => {
        const recur = (result,arr) => {
          if(arr.length===0){
            return result;
          }
          const randomIndex = Math.floor(Math.random() * arr.length);
          return recur(
            result.concat([arr[randomIndex]]),
            arr.filter((_,index)=>index!==randomIndex)
          );
        };
        return recur([],arr);
      }
      const array = [1,2,3,4,5];
      const shuffled = shuffle(array);
      console.log("array is:",array,"shuffled array is:",shuffled);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-25
        • 2017-12-09
        • 2020-01-12
        • 2017-09-13
        • 2020-05-13
        相关资源
        最近更新 更多