admin管理员组

文章数量:1287649

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];

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];

Share Improve this question asked Sep 22, 2020 at 22:47 marcin2x4marcin2x4 1,4493 gold badges29 silver badges56 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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

本文标签: Loop through array and replace value on condition in JavascriptStack Overflow