简体   繁体   中英

Loop through array and replace value on condition in Javascript

My array and pseudo code are as follows. I do need help with replacing values with stirng on condition. I tried below but can't move on.

var = [5000, 2000, 4030, 1100];

for (var i = 0; i < arR.length; i++) {
    if (arR.includes >= 5000) {
        (‘senior’);
    } else if (arR.includes >= 2000) {
        console.log(‘mid’);
    } else {
        (‘junior’);
    }
}

Expected result: var = [senior, mid, mid, junior];

 let array = [5000, 2000, 4030, 1100]; let TransformedArray = array.map(item=>item>=5000 ? 'senior' : item>=2000 ? 'mid' : 'junior'); console.log(TransformedArray);

You can do that with Array.map() and use any conditional operator to filter the result im using ternary here.

 var someArray = [5000, 2000, 4030, 1100]; var anotherArray = someArray.map(function (rank) { return rank >= 5000 ? 'senior' : rank >= 2000 ? 'mid' : 'junior'; }); console.log(anotherArray);

if you need it this way for easy understanding of if else and for each

 var someArray = [5000, 2000, 4030, 1100]; var newArray = []; someArray.forEach(function (rank) { if (rank >= 5000) { newArray.push('senior'); } else if (rank >= 2000) { newArray.push('mid'); } else { newArray.push('junior'); } }); console.log(newArray);

var array = [5000, 2000, 4030, 1100];

function converter(item) {
  return item >= 5000 && 'senior' || item >= 2000 && 'mid' || item >= 0 && 'junior';
}

var newArray = array.map(converter)
console.log(newArray);

The function returns false if an element is not a number (or smaller than 0). If you want to change that, you should cover the return with an if statement.

Just replace that element in the array, also iterate through the actual elements in your for-loop instead of checking if the value exists

var arR = [5000, 2000, 4030, 1100];

for (var i = 0; i < arR.length; i++) {
    if (arR[i] >= 5000) {
        arR[i] = "senior";
    } else if (arR[i] >= 2000) {
        arR[i] = "mid"
    } else {
        arR[i] = "junior"
    }
}

What I am doing here is checking each value, and if it satisfies a condition, then change it to the string it needs to be

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM