0

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) {

  const x = newArray.indexOf([i])
  console.log(x)
}

I'm a beginner at javascript and i cant understand why this code won't work. I am trying to produce this result in the simplest way possible:

0:4
1:-1
2:-1
3:-1
4:-1
5:-1 

Instead, it is iterating over the array and producing 6 x -1. even though the first element in the array does appear again. Appreciate any help in understanding why this happens and how to fix it

13
  • 1
    Why are you putting the index in an array? Even if it wasn't in an array, 0 should return -1, because it isn't in the array anyway Commented Dec 18, 2019 at 16:12
  • 1
    You should use newArray[i], instead. I'm not sure why you are doing this, though. It will just return the index of the first instance Commented Dec 18, 2019 at 16:16
  • 1
    I have no clue how ['t', 'r', 'c', 'g', 't', 'h'] is supposed to end up as 0:4, 1:-1, 2:-1, 3:-1, 4:-1, 5:-1 Commented Dec 18, 2019 at 16:22
  • 1
    I don't understand why people are answering a question with no clear outcome. Commented Dec 18, 2019 at 16:24
  • 1
    @Kobe He gives the input and the output, and this is the only logical way to produce that output, though I agree, the question should be more concise. And my code does produce the result (acutally, just copy paste it into your console...) Commented Dec 18, 2019 at 16:37

4 Answers 4

4

From what I understood, you want to find the first following position of a repeated item in an array sequence.

Original Answer

This can be done with findIndex, which takes a callback to determine if the index counts as found. Here you can specify that the items need to equal and the index needs to be greater than your current index, thus it is a repeated item.

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) { 
   // Find the index of the first item which index is greater than the current item and the latter equals the item
   const x = newArray
      .findIndex((item, index) => index > i && newArray[i] === item);

   console.log(`${i}: ${x}`);
}

Better Solution

As mentioned in the comments (thanks T.J. Crowder), indexOf takes a second parameter as an offset to start the search at. This is the preferrable solution, as it faster and more concise.

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) { 
   const x = newArray.indexOf(newArray[i], i+1); 
   console.log(`${i}: ${x}`);
}
Sign up to request clarification or add additional context in comments.

5 Comments

FWIW, findIndex is the wrong tool here, though it will work. If this is what the OP wants to do, they should just use indexOf's second argument: const x = newArray.indexOf(newArray[i], i + 1);
@T.J.Crowder You are right, honestly, didn't know indexOf had that second parameter. I'll change this one. Though, with findIndex it still works and it would be the right tool if it was more complex than just equallity.
:-) Yes, much the way that you can drive a nail with a wrench, but it's just a lot simpler with a hammer. Good edit!
thanks @pascalpuetz. appreciate you taking the time to answer
@chs242 You're welcome! If this is what you needed, could you mark the answer as correct? Cheers!
0

In the code above indexOf is searching for the location of i inside the array, and isn't finding it, as none of the array elements are numbers.

Try:

const x = newArray.indexOf(newArray[i])

Comments

0

The problem is that [i] in indexOf([i])is just an array with a number inside of it.

If you had indexOf(newArray[i]), then you would at least get the answer [0, 1, 2, 3, 0, 5] (the character will find itself, except the second t that finds the first t at position 0).

But I assume that you only want to know the position of the upcoming letter, and not the position of the previous ones.

What you can do is to loop from the end of the array instead, save each letter in an object with it's position and then replace it if the letter has already existed.

I will add the code in a method so it's easier to use it with other arrays.

function findOccurancies(newArray) {
  let newObj = {};
  let currentCharacter = '';
  let x = [];

  for (let i = newArray.length-1; i >= 0; i--) {
     currentCharacter = newArray[i];

     if (newObj.hasOwnProperty(currentCharacter)) {         
       x.unshift(newObj[currentCharacter]) // place the item first.
     } else {
       x.unshift(-1)                       // place the item first.
     }      

     newObj[currentCharacter] = i;
  }
  
  return x;
}

console.log(findOccurancies(['t', 'r', 'c', 'g', 't', 'h']));

console.log(findOccurancies(['t', 'r', 'c', 'g', 't', 'h', 't']));

Comments

-3

I don't understand, if you just want to print the array, you need to go directly to the position:

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) {

  const x = newArray[i]
  console.log(x)
}

And if you want to print the position of each value in the array, do it like this:

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) {

  const x = newArray.indexOf(newArray[i])
  console.log(x)
}

Hope it will help you.

Comments

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.