简体   繁体   中英

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.

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 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 });
function transform(str){
   //logic to transform goes here
}

var massaged = myArr.map(transform);

Maybe thats what youre asking for?

map reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM