let arrayOfNumbers = [1,2,3,4,5]
what would be the best way to compare the numbers against each other? For instance, comparing 1 to 2 then 2 to 3 then 3 to four, and so on?
function t(a) {
let t = 0
for (let i = 0; i < a.length; i ) {
if (a[t] > a[t 1]) {
console.log('down')
} else if (a[t] < a[t 1]) {
console.log('up')
} else if (a[t] === a[t 1]) {
console.log('no change')
}
t
} }
CodePudding user response:
You could start from index one and check the previous value.
function t(a) {
for (let i = 1; i < a.length; i ) {
if (a[i - 1] > a[i]) console.log('down');
else if (a[i - 1] < a[i]) console.log('up');
else console.log('no change');
}
}
t([0, 1, 3, 2, 4, 4, 2]);
CodePudding user response:
I would do a for loop(since you don't describe why you need it I will have it to see if they are all the same, also I may have misunderstood the question, if I did it should be changeable to fit what you need)
var Numbers = [1,1,1,1,1,0,1,1];
//I am using this for the exsample
for (i=0;i<Numbers.length-1;i ){
//the minus one is so it dosn't do 1 isn't the same as undefined
if (Numbers[i]==Numbers[i 1]){
console.log(String(Numbers[i]) ' is the same as ' String(Numbers[i 1]));
//this is for when the numbers are the same
} else{
console.log(String(Numbers[i]) ' is different than ' String(Numbers[i 1]));
//the is for when the numbers are different
}
}
sorry if this is a weird format, this is my first time answering a question on StackOverflow