Reputation: 1124
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?
Upvotes: 1
Views: 64
Reputation: 3764
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;
}
Upvotes: 1
Reputation: 31
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;
}
Upvotes: 1
Reputation: 370819
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])
);
Upvotes: 6