3

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

4 Answers 4

6

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

let TransformedArray = array.map(item=>item>=5000 ? 'senior' : item>=2000 ? 'mid' : 'junior');

console.log(TransformedArray);

Sign up to request clarification or add additional context in comments.

3 Comments

I understand correctly that item=>item is arrow function?
Yes it is. When there is one line there's no need (illegal) to use return keyword.
Do you have an article that explains arrow function in detail? They are quite bugging me to understand. Thanks!
2

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

Comments

1
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.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.