admin管理员组

文章数量:1022997

I need to find first two numbers and show index like:

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

so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex

for (i = numbers[0]; i <= numbers.length; i++) {
  firstIndex = numbers[0]
  if (numbers[i] == firstIndex) {
    console.log(firstIndex);
    break;
  }
}

I need to find first two numbers and show index like:

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

so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex

for (i = numbers[0]; i <= numbers.length; i++) {
  firstIndex = numbers[0]
  if (numbers[i] == firstIndex) {
    console.log(firstIndex);
    break;
  }
}

Share Improve this question edited Apr 4, 2018 at 3:34 user6655984 asked Jan 5, 2017 at 9:46 RafalRafRafalRaf 131 silver badge3 bronze badges 3
  • is there any restriction on range of numbers? – instance Commented Jan 5, 2017 at 9:50
  • @Bálint - Teacher says they have to use a 'for' loop... ;o) – allnods Commented Jan 5, 2017 at 9:53
  • in your first example the first repeated number i see is 5! – Jamiec Commented Jul 16, 2019 at 15:04
Add a ment  | 

12 Answers 12

Reset to default 2

You can use Array#indexOf method with the fromIndex argument.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];

// iterate upto the element just before the last
for (var i = 0; i < numbers.length - 1; i++) {
  // check the index of next element
  if (numbers.indexOf(numbers[i], i + 1) > -1) {
    // if element present log data and break the loop
    console.log("index:", i, "value: ", numbers[i]);
    break;
  }
}


UPDATE : Use an object to refer the index of element would make it far better.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
  ref = {};

// iterate over the array
for (var i = 0; i < numbers.length; i++) {
  // check value already defined or not
  if (numbers[i] in ref) {
    // if defined then log data and brek loop
    console.log("index:", ref[numbers[i]], "value: ", numbers[i]);
    break;
  }
  // define the reference of the index
  ref[numbers[i]] = i;
}

Many good answers.. One might also do this job quite functionally and efficiently as follows;

var arr = [2,5,5,2,3,5,1,2,4],
   frei = arr.findIndex((e,i,a) => a.slice(i+1).some(n => e === n)); // first repeating element index
console.log(frei)

If might turn out to be efficient since both .findIndex() and .some() functions will terminate as soon as the conditions are met.

You could use two for loops an check every value against each value. If a duplicate value is found, the iteration stops.

This proposal uses a labeled statement for breaking the outer loop.

var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
    i, j;

outer: for (i = 0; i < numbers.length - 1; i++) {
    for (j = i + 1; j < numbers.length; j++) {
        if (numbers[i] === numbers[j]) {
            console.log('found', numbers[i], 'at index', i, 'and', j);
            break outer;
        }
    }
} 

Move through each item and find if same item is found on different index, if so, it's duplicate and just save it to duplicate variable and break cycle

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var duplicate = null;
for (var i = 0; i < numbers.length; i++) {
  if (numbers.indexOf(numbers[i]) !== i) {
    duplicate = numbers[i];
    break; // stop cycle 
  }
}
console.log(duplicate);

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var map = {};
    
for (var i = 0; i < numbers.length; i++) {
   if (map[numbers[i]] !== undefined) {
       console.log(map[numbers[i]]);
       break;
   } else {
       map[numbers[i]] = i;
   }
}

Okay so let's break this down. What we're doing here is creating a map of numbers to the index at which they first occur. So as we loop through the array of numbers, we check to see if it's in our map of numbers. If it is we've found it and return the value at that key in our map. Otherwise we add the number as a key in our map which points to the index at which it first occurred. The reason we use a map is that it is really fast O(1) so our overall runtime is O(n), which is the fastest you can do this on an unsorted array.

As an alternative, you can use indexOf and lastIndexOf and if values are different, there are multiple repetition and you can break the loop;

function getFirstDuplicate(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])) 
      return arr[i];
  }
}

var arrWithNumbers = [2, 5, 5, 2, 3, 5, 1, 2, 4];
console.log(getFirstDuplicate(arrWithNumbers))

var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11]
console.log(getFirstDuplicate(numbers))

I have the same task and came up with this, pretty basic solution:

var arr = [7,4,2,4,5,1,6,8,9,4];
var firstIndex = 0;

for(var i = 0; i < arr.length; i++){
  for( var j = i+1; j < arr.length; j++){
    if(arr[i] == arr[j]){
      firstIndex = arr[i];
      break;      
    }

  }
}
console.log(firstIndex);

First for loop takes the first element from array (number 7), then the other for loop checks all other elements against it, and so on.

Important here is to define j in second loop as i+1, if not, any element would find it's equal number at the same index and firstIndex would get the value of the last one after all loops are done.

To reduce the time plexity in the aforementioned answers you can go with this solution:

function getFirstRecurringNumber(arrayOfNumbers) {
  const hashMap = new Map();

  for (let number of arrayOfNumbers) { // Time plexity: O(n)
    const numberDuplicatesCount = hashMap.get(number);

    if (numberDuplicatesCount) {
      hashMap.set(number, numberDuplicatesCount + 1);

      continue;
    }

    hashMap.set(number, 1); // Space plexity: O(n)
  }

  for (let entry of hashMap.entries()) { // Time plexity: O(i)
    if (entry[1] > 1) {
      return entry[0];
    }
  }
}

// Time plexity: O(n + i) instead of O(n^2)
// Space plexity: O(n)

Using the code below, I am able to get just the first '5' that appears in the array. the .some() method stops looping through once it finds a match.

let james = [5, 1, 5, 8, 2, 7, 5, 8, 3, 5];
let onlyOneFives = [];
james.some(item =>  {
    //checking for a condition. 
    if(james.indexOf(item) === 0) {
        //if the condition is met, then it pushes the item to a new array and then   
        //returns true which stop the loop

        onlyOneFives.push(item);
         return james.indexOf(item) === 0;
   }
})

console.log(onlyOneFives)

Create a function that takes an array with numbers, inside it do the following: First, instantiate an empty object. Secondly, make a for loop that iterates trough every element of the array and for each one, add them to the empty object and check if the length of the object has changed, if not, well that means that you added a element that already existed so you can return it:

//Return first recurring number of given array, if there isn't return undefined.

const firstRecurringNumberOf = array =>{
    objectOfArray = {};

    for (let dynamicIndex = 0; dynamicIndex  < array.length; dynamicIndex ++) {
        const elementsBeforeAdding = (Object.keys(objectOfArray)).length;0
        objectOfArray[array[dynamicIndex]] = array[dynamicIndex]
        const elementsAfterAdding = (Object.keys(objectOfArray)).length;

        if(elementsBeforeAdding == elementsAfterAdding){ //it means that the element already existed in the object, so it didnt was added & length doesnt change.
             return array[dynamicIndex];
        }
    }

    return undefined;
}

console.log(firstRecurringNumberOf([1,2,3,4])); //returns undefined
console.log(firstRecurringNumberOf([1,4,3,4,2,3])); //returns 4

const arr = [1,9,5,2,3,0,0];
const copiedArray = [...arr];
const index = arr.findIndex((element,i) => { 
 copiedArray.splice(0,1);
 return copiedArray.includes(element)
})
    
console.log(index);

var addIndex = [7, 5, 2, 3, 4, 5, 7,6, 2];
var firstmatch = [];
for (var i = 0; i < addIndex.length; i++) {

    if ($.inArray(addIndex[i], firstmatch) > -1) {
        return false;
    }
    firstmatch.push(addIndex[i]);
}

I need to find first two numbers and show index like:

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

so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex

for (i = numbers[0]; i <= numbers.length; i++) {
  firstIndex = numbers[0]
  if (numbers[i] == firstIndex) {
    console.log(firstIndex);
    break;
  }
}

I need to find first two numbers and show index like:

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

so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex

for (i = numbers[0]; i <= numbers.length; i++) {
  firstIndex = numbers[0]
  if (numbers[i] == firstIndex) {
    console.log(firstIndex);
    break;
  }
}

Share Improve this question edited Apr 4, 2018 at 3:34 user6655984 asked Jan 5, 2017 at 9:46 RafalRafRafalRaf 131 silver badge3 bronze badges 3
  • is there any restriction on range of numbers? – instance Commented Jan 5, 2017 at 9:50
  • @Bálint - Teacher says they have to use a 'for' loop... ;o) – allnods Commented Jan 5, 2017 at 9:53
  • in your first example the first repeated number i see is 5! – Jamiec Commented Jul 16, 2019 at 15:04
Add a ment  | 

12 Answers 12

Reset to default 2

You can use Array#indexOf method with the fromIndex argument.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];

// iterate upto the element just before the last
for (var i = 0; i < numbers.length - 1; i++) {
  // check the index of next element
  if (numbers.indexOf(numbers[i], i + 1) > -1) {
    // if element present log data and break the loop
    console.log("index:", i, "value: ", numbers[i]);
    break;
  }
}


UPDATE : Use an object to refer the index of element would make it far better.

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
  ref = {};

// iterate over the array
for (var i = 0; i < numbers.length; i++) {
  // check value already defined or not
  if (numbers[i] in ref) {
    // if defined then log data and brek loop
    console.log("index:", ref[numbers[i]], "value: ", numbers[i]);
    break;
  }
  // define the reference of the index
  ref[numbers[i]] = i;
}

Many good answers.. One might also do this job quite functionally and efficiently as follows;

var arr = [2,5,5,2,3,5,1,2,4],
   frei = arr.findIndex((e,i,a) => a.slice(i+1).some(n => e === n)); // first repeating element index
console.log(frei)

If might turn out to be efficient since both .findIndex() and .some() functions will terminate as soon as the conditions are met.

You could use two for loops an check every value against each value. If a duplicate value is found, the iteration stops.

This proposal uses a labeled statement for breaking the outer loop.

var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
    i, j;

outer: for (i = 0; i < numbers.length - 1; i++) {
    for (j = i + 1; j < numbers.length; j++) {
        if (numbers[i] === numbers[j]) {
            console.log('found', numbers[i], 'at index', i, 'and', j);
            break outer;
        }
    }
} 

Move through each item and find if same item is found on different index, if so, it's duplicate and just save it to duplicate variable and break cycle

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var duplicate = null;
for (var i = 0; i < numbers.length; i++) {
  if (numbers.indexOf(numbers[i]) !== i) {
    duplicate = numbers[i];
    break; // stop cycle 
  }
}
console.log(duplicate);

var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var map = {};
    
for (var i = 0; i < numbers.length; i++) {
   if (map[numbers[i]] !== undefined) {
       console.log(map[numbers[i]]);
       break;
   } else {
       map[numbers[i]] = i;
   }
}

Okay so let's break this down. What we're doing here is creating a map of numbers to the index at which they first occur. So as we loop through the array of numbers, we check to see if it's in our map of numbers. If it is we've found it and return the value at that key in our map. Otherwise we add the number as a key in our map which points to the index at which it first occurred. The reason we use a map is that it is really fast O(1) so our overall runtime is O(n), which is the fastest you can do this on an unsorted array.

As an alternative, you can use indexOf and lastIndexOf and if values are different, there are multiple repetition and you can break the loop;

function getFirstDuplicate(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])) 
      return arr[i];
  }
}

var arrWithNumbers = [2, 5, 5, 2, 3, 5, 1, 2, 4];
console.log(getFirstDuplicate(arrWithNumbers))

var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11]
console.log(getFirstDuplicate(numbers))

I have the same task and came up with this, pretty basic solution:

var arr = [7,4,2,4,5,1,6,8,9,4];
var firstIndex = 0;

for(var i = 0; i < arr.length; i++){
  for( var j = i+1; j < arr.length; j++){
    if(arr[i] == arr[j]){
      firstIndex = arr[i];
      break;      
    }

  }
}
console.log(firstIndex);

First for loop takes the first element from array (number 7), then the other for loop checks all other elements against it, and so on.

Important here is to define j in second loop as i+1, if not, any element would find it's equal number at the same index and firstIndex would get the value of the last one after all loops are done.

To reduce the time plexity in the aforementioned answers you can go with this solution:

function getFirstRecurringNumber(arrayOfNumbers) {
  const hashMap = new Map();

  for (let number of arrayOfNumbers) { // Time plexity: O(n)
    const numberDuplicatesCount = hashMap.get(number);

    if (numberDuplicatesCount) {
      hashMap.set(number, numberDuplicatesCount + 1);

      continue;
    }

    hashMap.set(number, 1); // Space plexity: O(n)
  }

  for (let entry of hashMap.entries()) { // Time plexity: O(i)
    if (entry[1] > 1) {
      return entry[0];
    }
  }
}

// Time plexity: O(n + i) instead of O(n^2)
// Space plexity: O(n)

Using the code below, I am able to get just the first '5' that appears in the array. the .some() method stops looping through once it finds a match.

let james = [5, 1, 5, 8, 2, 7, 5, 8, 3, 5];
let onlyOneFives = [];
james.some(item =>  {
    //checking for a condition. 
    if(james.indexOf(item) === 0) {
        //if the condition is met, then it pushes the item to a new array and then   
        //returns true which stop the loop

        onlyOneFives.push(item);
         return james.indexOf(item) === 0;
   }
})

console.log(onlyOneFives)

Create a function that takes an array with numbers, inside it do the following: First, instantiate an empty object. Secondly, make a for loop that iterates trough every element of the array and for each one, add them to the empty object and check if the length of the object has changed, if not, well that means that you added a element that already existed so you can return it:

//Return first recurring number of given array, if there isn't return undefined.

const firstRecurringNumberOf = array =>{
    objectOfArray = {};

    for (let dynamicIndex = 0; dynamicIndex  < array.length; dynamicIndex ++) {
        const elementsBeforeAdding = (Object.keys(objectOfArray)).length;0
        objectOfArray[array[dynamicIndex]] = array[dynamicIndex]
        const elementsAfterAdding = (Object.keys(objectOfArray)).length;

        if(elementsBeforeAdding == elementsAfterAdding){ //it means that the element already existed in the object, so it didnt was added & length doesnt change.
             return array[dynamicIndex];
        }
    }

    return undefined;
}

console.log(firstRecurringNumberOf([1,2,3,4])); //returns undefined
console.log(firstRecurringNumberOf([1,4,3,4,2,3])); //returns 4

const arr = [1,9,5,2,3,0,0];
const copiedArray = [...arr];
const index = arr.findIndex((element,i) => { 
 copiedArray.splice(0,1);
 return copiedArray.includes(element)
})
    
console.log(index);

var addIndex = [7, 5, 2, 3, 4, 5, 7,6, 2];
var firstmatch = [];
for (var i = 0; i < addIndex.length; i++) {

    if ($.inArray(addIndex[i], firstmatch) > -1) {
        return false;
    }
    firstmatch.push(addIndex[i]);
}

本文标签: Find the first repeated number in a Javascript arrayStack Overflow