let a = [33, 15, 67, 203450, 212]
Above is the array that I am working with. I need to compare every previous element to the next one till the last element of the array. If the element is bigger than the one before it I add 2 into the "myNums". If the element is smaller than the one before it I add 1 into the "myNums". If the element equals the element before it I add 0 into the "myNums".
I made 3 functions to get me the sum of the digits I pushed into "myNums", but none of them works. So, how do I do this ?
Below are the functions I made to solve my problem.
function b(cmp) {
for (let c = 0; c < cmp.length; c++) {
let A = cmp[c]
let B = cmp[c + 1]
let myNums = []
if (A < B) {
myNums.push(1)
}
else if (A > B) {
myNums.push(2)
}
else {
myNums.push(0)
}
let sum = 0
console.log(myNums)
for (let d = 0; d < myNums.length; d++) {
sum += myNums[d];
}
return sum
}
}
let d = b(a)
console.log(d)
////////////////////////////////////////////////////////////////////////////////////
function b(cmp) {
while ((c = 0) && (c < cmp.length)) {
let A = cmp[c]
let B = cmp[c + 1]
let myNums = []
while ((A < B) || (A > B) || A == B) {
if (A < B) {
myNums.push(1)
}
else if (A > B) {
myNums.push(2)
}
else {
myNums.push(0)
}
}
let sum = 0
for (let d = 0; d < myNums.length; d++) {
sum += myNums[d];
}
return sum
}
c++
}
let d = b(a)
console.log(d)
//////////////////////////////////////////////////////////////////////////////////////
function b(cmp) {
for (let c = 0; c < cmp.length; c++) {
let A = cmp[c]
let B = cmp[c + 1]
let C = []
let D = 0
switch (B) {
case (A < B):
C.push(1)
case (A > B):
C.push(2)
case (A == B):
C.push(0)
}
for (let d = 0; d < C.length; d++) {
D += C[d];
}
return C
}
}
let e = b(a)
console.log(e)
They gave me either 0 or 1 or an empty array in the console.
2
Answers
this code will compare the array
loop the element and check each one
You could sliche the array and map the result by taking the sign of the delta with adjustments.
A slightly better approach by taking an object for values.