Assuming you have an object with the replacing to do, you can use Array.map
var replace = {
'cat': 'tiger',
'dog': 'wolf',
'cow': 'diary',
};
var starter = ["cat", "dog", "cow"];
var final = starter.map(value => replace[value] || value);
console.log(final)
If the string is not in the replace object, replace[value] is undefined, so replace[value] || value is evaluet do value itself.
Anyway, the for is definitely more performing, at least on node.js, accordingly to benchmark.js:
Array.map x 2,818,799 ops/sec ±1.90% (76 runs sampled)
for array x 9,549,635 ops/sec ±1.86% (79 runs sampled)
Fastest is for array
Here the code I used for the test
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
suite
.add('Array.map', function() {
var replace = {
'cat': 'tiger',
'dog': 'wolf',
'cow': 'diary',
};
var starter = ["cat", "dog", "cow"];
var final = starter.map(value => replace[value] || value);
})
.add('for array', function() {
var replace = {
'cat': 'tiger',
'dog': 'wolf',
'cow': 'diary',
};
var starter = ["cat", "dog", "cow"];
var final = [];
for (var i = 0; i < starter.length; i++) {
final.push(replace[starter[i]] || starter[i]);
}
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });