DEV Community

loading...
Cover image for Day 18 of JavaScriptmas - Array Previous Less

Day 18 of JavaScriptmas - Array Previous Less

Sekti
Keep moving forward. Learn well not learn fast.
・1 min read

Day 18 is to check the previous index of the array is less than the current index of the array.

For example, an array of [3, 5, 2, 4, 5] will return [-1, 3, -1, 2, 4].

From the array above if the previous index (3) less than the current index (5) return the previous index (3), but if previous index (5) is not less than current index (2), return -1;

These are the solution in JavaScript

1st - Using Unshift

function arrayPreviousLess(nums) {
    let result = [];
    for (i=nums.length-1; i >= 0; i--) {
        (nums[i] > nums[i-1]) ? result.unshift(nums[i-1]) : result.unshift(-1);
    }
    return result;   
}
Enter fullscreen mode Exit fullscreen mode

When using Unshift, it starts from the last index and insert value on the beginning of the array on each iteration.

Meanwhile....

2nd - Using Push

function arrayPreviousLess(nums) {
    let result = [];

    for (i=0; i < nums.length; i++) {
        (nums[i-1] < nums[i]) ? result.push(nums[i-1]) : result.push(-1);
    }

    return result;   
}
Enter fullscreen mode Exit fullscreen mode

When using Push, it starts the index from 0 and insert value on the last of the array on each iteration.

Discussion (0)