1

The problem I have to solve is the following -

splitEven(a) – The function accepts an array of integers and would return an array that contains the values that are located in the even indices of the original array, sorted in ascending order. For example, if the function gets the array [3, 1, 6, 7, 4] it would return the array [3, 4, 6]

This is my solution -

    function splitEven(a){
    var b = [];
    var even = function(element){
        return element % 2 === 0;
    }
    for (var i = 0; i < a.length; i++) {
        var c = even(a[i]);
        if (c) {
            b.push(a[i])
        }
    }
    return b;
}

However I feel it is not best practice to do what I have done. I am familier with Java, and I think I tend to solve problems not in the right way.

Can you think of a better approach for this problem, to improve my practice?

3 Answers 3

6

You can use filter to create an array that contains only the even-numbered indicies in the original array, and then sort() that array:

const splitEven = arr => arr
  .filter((_, i) => i % 2 === 0)
  .sort((a, b) => a - b);

console.log(
  splitEven([3, 1, 6, 7, 4])
);
console.log(
  splitEven([3, 1, 6, 7, 4, 11, 12])
);

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

Comments

1

Another approach to simplify your code is to use an IF statement nested in your FOR loop.

function splitEven(array) {
  var even = [];

  for (let i = 0; i < array.length; i++) {
    if (array[i] % 2 == 0) {
      even.push(array[i]);
    }
  }
  return even;
}

2 Comments

Thank you, indeed nicer.
That checks, if the element of the array is even and not if the index is.
1

You could just increase by 2 instead of 1 and in the end use sort().

function splitEven(array){
    var b = [];
    for (i = 0; i < array.length; i += 2){
      b.push(array[i]);
    }

    b.sort((a,b) => {return a-b;});

    return b;
}

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.