False语句返回一个空数组

时间:2018-09-07 03:40:13

标签: javascript

因此,我尝试编写一个代码,如果有重复的数字,则返回true,如果没有重复,则返回false。我让重复项出现,但是如果没有重复项,我希望它返回单词false。这是我缺少的代码。

var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];

var uniqueArray = numbers.map((number) => {
return {count:1, number: number}
})
.reduce((a, b) => {
a[b.number] = (a[b.number] || 0) + b.count
return a
}, {})

var duplicate = Object.keys(uniqueArray ).filter((a) => uniqueArray [a] > 1)

//console.log(duplicate)

function hasDuplicates(){
  if (duplicate = true) {
    return true
  }
}

5 个答案:

答案 0 :(得分:0)

function hasDuplicates(){ if (duplicate = true) { return true } }

声明

duplicate = true

意味着“为变量duplicate赋值true并返回true。这不是您想要的。

答案 1 :(得分:0)

我尝试了您的代码,如果没有重复,则会得到一个空数组 所以我要重写hasDuplicates函数

function hasDuplicates(){
  return duplicate.length === 0
}

答案 2 :(得分:0)

使用Array.from(new Set(array))创建唯一的数组,然后比较两个数组的长度。如果唯一数组的元素较少,则为重复!

var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];
//console.log(numbers);
var uniqueArrays = Array.from(new Set(numbers));
if (uniqueArrays.length < numbers.length)
    console.log('Has duplicate!');
else
    console.log('No duplicate!');

答案 3 :(得分:0)

您可以使用Array#someArray#everyArray#filter简化此操作。

JS Perf

如果您不在乎实际的重复值

使用Array#some

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

const hasDuplicates = numbers.some((number, index, a) => numbers.indexOf(number) !== index);

console.log(hasDuplicates);

使用Array#every

var numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

var hasDuplicates = !numbers.every((number, index) => numbers.indexOf(number) === index);

console.log(hasDuplicates);

使用Array#filter

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];
const uniques = numbers.filter((number, index) => numbers.indexOf(number) === index);
const hasDuplicates = numbers.length !== uniques.length;

console.log(uniques, hasDuplicates);

如果您愿意的话

const numbers = [14, 50, 27, 52, 25, 41, 5, 9, 25, 10, 25, 6];

const duplicates = [];

const uniques = numbers.filter((number, index) => {
  return numbers.indexOf(number) === index || !duplicates.includes(number) && duplicates.push(number) && false;
});

function hasDuplicates(){
  return !!duplicates.length;
}

console.log(duplicates, uniques, hasDuplicates());
    

答案 4 :(得分:-1)

function hasDuplicates() {
  return duplicate ? 'true' : 'false';
}

var numbers= [14, 50, 27, 52,  41, 5, 9, 25, 10, 6];
var unique = {};
numbers.forEach( n => { unique[n] = 1; } );
var duplicate = numbers.length != unique.length;