Javascript:没有重复的随机字符串数组

时间:2018-05-03 03:59:20

标签: javascript arrays string random

我试图从此随机生成器数组中删除重复项。我已经尝试了许多不同的代码行,可以删除重复但我还没有能够得到任何工作。

我使用过的例子:

        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"; 

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:-1)

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



//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);