0

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

3
  • is there any restriction on range of numbers? Commented Jan 5, 2017 at 9:50
  • @Bálint - Teacher says they have to use a 'for' loop... ;o) Commented Jan 5, 2017 at 9:53
  • in your first example the first repeated number i see is 5! Commented Jul 16, 2019 at 15:04

12 Answers 12

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

Sign up to request clarification or add additional context in comments.

4 Comments

This is going to be O(n^2) runtime
This one is wrong, it gives invalid result, why upvoting invalid code?
@LukasLiesis Pranav has logged index and not number. That is why you see incorrect output. Please check my edit
object.hasOwnProperty() is almost never needed in current JS code. A key in object test suffices just as well
2

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.

1 Comment

This will be very expensive. findIndex + slice + some
1

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

2 Comments

Can you explain me what doing the outer function?
outer is a label for the following loop statement. the idea is to stop both for loops if a result is found. the first iterates the array and the second checks if an item of the rest of the array is equal to the elment of the outer element. the startinf index of the inner for loop is one greater than the outer loop index, because it prevents to compare items at the same index.
0

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

Comments

0

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.

Comments

0

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

Comments

0

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.

2 Comments

this seems to work sometimes and sometimes not. anyone has a comment on this?
it only shows the last number that has a duplicate, so it works only if there is one pair of equal numbers in the array
0

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

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

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

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

      continue;
    }

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

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

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

Comments

0

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)

Comments

0

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

Comments

0

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

Comments

-1
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]);
}

5 Comments

First explanation missing. Second, you can initialise firstIndex as numbers[0] and start loop from 1. Also not sure if this will work correctly
Please add 1 at the start of the array and rerun it. Your algo is only checking for first element.
can you edit then edit and change it..if i m doing something wrong
Please see other answers. Pranav's answer shows 2 very good approach. You can check my answer for alternate approach. There is no need to include any library to achieve this task
Usually it is a good idea to add an explanation to your post that talks about how the code works. This allows new developers to understand what the code does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.