2

Not sure why this isn't working.

Instructions:

// Create a function called indexFinder that will loop over an array and return a new array of the indexes of the contents e.g. [243, 123, 4, 12] would return [0,1,2,3]. Create a new variable called 'indexes' and set it to contain the indexes of randomNumbers.

Tried Solution:

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];

function indexFinder(arr){
  for(var i = 0; arr.length; i++){
    indexes.push(i);
  }

  return indexes;
}

indexFinder(randomNumbers);
console.log(indexes);

3 Answers 3

2

You have no real condition test in your for loop because arr.length, when above 0, is always truthy.

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];

function indexFinder(arr){
  for(var i = 0; i < arr.length; i++){
    indexes.push(i);
  }

  return indexes;
}

indexFinder(randomNumbers);
console.log(indexes);

But there's a much more concise way of doing this:

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
const indexFinder = arr => arr.map((_, i) => i);
console.log(indexFinder(randomNumbers));

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

1 Comment

Or Object.keys(arr) ...though I guess they'd be strings, so Object.keys(arr).map(Number)
2

Another method is using Array.from

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log(Array.from(randomNumbers, x => randomNumbers.indexOf(x)));

Or we can use keys

const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log([...Array(randomNumbers.length).keys()])

Comments

1

The problem is the condition within that for-loop using just arr.length because for length greater than 0 will be always true.

An alternative is using the function Array.from:

let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0],
    indexes = Array.from({length: randomNumbers.length}, (_, i) => i);
    
console.log(indexes);

Another alternative is getting the length and then execute a simple for-loop.

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.