1

I don't understand well this exercise.

arr = [1, 2, 3];
arr.indexOf(2); // 1
arr.indexOf(4); // -1 since it doesn't exist.

// Write a function to determine if an element
// is in the first half of an array.
// If an element has an odd length, round up
// when counting the first half of an array.
// For example, 1 and 2 are in the first half
// arr.
function inFirstHalf(inputArray, element) {

}

I don't got it, what does mean first half of an array?

3
  • 1
    I guess it means if indexOf returns a value that is less than half of arr.length, rounded up if length is odd (which means you'll actually have to round down, since array indexes start at 0). Commented Nov 4, 2015 at 2:01
  • @RobG you made my day! Commented Nov 4, 2015 at 2:05
  • Thank you @RobG, I am taking this course codecademy.com/courses/javascript-intro/8/4, I was stuck in that exercise. Commented Nov 4, 2015 at 2:07

2 Answers 2

2

Look up the value in a new array created by slicing the original array in two:

arr.slice(0, Math.ceil(arr.length/2)) . indexOf(val)
Sign up to request clarification or add additional context in comments.

Comments

-1

You should retrieve the length of the array arr using the length property. Now you have to check whether the element index is smaller than length and round up when length is odd.

function inFirstHalf(inputArray, element) {
    if ((inputArray.length % 2) === 0) {
        if ((inputArray.indexOf(element) + 1) <= (inputArray.length / 2)) {
            return true;
        }
    } else {
        if ((inputArray.indexOf(element) + 1) <= Math.ceil ((inputArray.length / 2))) {
            return true;
        }
    }
    return false;
}

3 Comments

Could you show some examples of how you tested this?
If the index is less than inputArray.length / 2, then by definition it will also be less than the ceiling of that value, so the second check would seem to be unnecessary, unless I'm missing something.
In this approach the second check is necessary due to the first if statement. The first step is to check whether the array length is odd or not. When the length is not odd the inputArray.length / 2 check applies. Otherwise (when the array length is odd) the Math.ceil check applies. Even if this approach isn't the best (nor a good) one, the task will be solved with the suggested techniques of codeacadamy (and that's what this excercise is for).

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.