Day 18 — Scrimba JavaScriptmas (Array Previous Less)

Handhika Yanuar Pratama
2 min readDec 18, 2020

--

Perhaps i was late for joining this challenge but, it’s okay, nothing is never late, unless we do nothing. So i skipped all day and jumped into day 18.

The challenge of this day is to check previous index of the array, if it’s less than the current index of an array. The question is simple, It just how to make array of [3, 5, 2, 4, 5 ] will give the answer of [-1, 3, -1, 2, 4]

As we know the index 0 of array is 3, and the left side of 3 is nothing so it will turn into -1. Next the index 1 of array is 5, and 5 is bigger than 3, so it will become 3. Next the index 2 of array is 2, and the left index of 2 is nothing smaller than it, so the index will change to be -1. And so on.

There are many solution to finish this challenge, the hints of this challenge is using unshift(). But i try another way, i use push() method and hope this will make a sense for you all :

function arrayPreviousLess(nums) {newNumber = []
for(i=0; i<nums.length; i++){ if(nums[i] > nums[1-1]){ newNumber.push(nums[i-1]) }else{ newNumber.push(-1) }}return newNumber}

So this is my explanation:
1. First we declare an empty array into a variable
2. Using for loops to move around within the originals arrays
3. Using if statement if the index of active array is greater than the array before it
4. If true it will push the number of array before to be the active array
5. If false, the active array will change to be -1
6. Last, using return the result of array that we declared in number 1

input :
console.log(arrayPreviousLess([3, 5, 2, 4, 5]))
output :
[-1, 3, -1, 2, 4]

Thank you

#JavaScriptmas #scrimba #24DaysChallenge #javascript #newbie #programmer

--

--