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];
4 Answers
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
版权声明:本文标题:Loop through array and replace value on condition in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741317539a2372007.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论