javascript - 如何找到数组中的第一个频率值?

标签 javascript arrays

我有一个包含对象的数组。我需要在循环中找到第一个重复值。我想我需要使用 break,但它不起作用。

这是我的代码:

var arrWithNumbers = [2,4,5,2,3,5,1,2,4];
var firstIndex = 0;

for(var i=0; i<10; i++) {
  if(arrWithNumbers.length == firstIndex[i]) {
    firstIndex = arrWithNumbers;
    break;
  }
}

console.log(firstIndex);

最佳答案

您可以循环直到获得与实际索引相同编号的索引。

本提案使用Array#indexOf fromIndex 大于实际索引。

var array = [2, 4, 5, 2, 3, 5, 1, 2, 4],
    index = 0,
    second;
    
while (index < array.length) {
    second = array.indexOf(array[index], index + 1);
    if (second !== -1) {
        break;
    }
    index++;
}

console.log(index);
console.log(second);

哈希表方法

var array = [2, 4, 5, 2, 3, 5, 1, 2, 4],
    index = 0,
    hash = Object.create(null);
    
while (index < array.length) {
    if (array[index] in hash) {
        break;
    }
    hash[array[index]] = index;
    index++;
}

console.log(hash[array[index]], index);

关于javascript - 如何找到数组中的第一个频率值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868960/

相关文章:

用于事件处理的 JavaScript 库出现奇怪的 'undefined' 错误

javascript - : $(this. el).html 和 this.$el.html 有什么区别

javascript - 背景滚动与内容匹配的顶部和底部?

javascript - PHP/Javascript - 从巨大的日志文件中实时读取添加的行

javascript - 是否可以在具有本地数据的剑道网格中拥有完整的 CRUD 功能

php - 传递复选框输入数组值以根据选择插入 MySQL 查询

java - Android 数组不工作的测验

java - 我想从textView保存数据。它可以保存数据,但是在文件中只有一个数据

php - 将非关联数组传递给 json_encode() 时会发生什么?

Java:声明一个大小为 n 的数组的大 O 时间是多少?