lost9123193 lost9123193 - 4 months ago 7
Javascript Question

Improved Method of Finding and replacing Strings in an Array in Javascript

I have the following array:

["cat", "dog", "cow"]


I want to replace the values of each with a new string.

["tiger", "wolf", "diary"]


Currently I am traversing through a for loop and checking to see if a string that needs its name to be changed exists, if it does then I am replacing it with the new value. While a for loop works, I am wondering if there's a nicer way of doing this.

Answer

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,915,917 ops/sec ±1.80% (78 runs sampled)
for array x 34,320,038 ops/sec ±1.44% (76 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; 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 });