2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでfilterしてmapを実行したい

Last updated at Posted at 2018-04-27

配列にダブルクォートで囲われた動物達がいます。
重複をなくして、さらにダブルクォートを取り除きたい。普通にfilterとmapでやると

let animals = ['"cat"', '"dog"', '"cat"', '"bird"', '"dog"'];

// filterで重複を取り除いてからmapで文字列置き換え
animals = animals.filter(function(element, index, array) {
  return array.indexOf(element) === index;
}).map(function(element) {
  return element.replace(/"/g, '');
});
=> [ 'cat', 'dog', 'bird' ]

もうちょっとエレガントに書けないかと思い関数化してすっきり!

let unique = function(element, index, array) {
  return array.indexOf(element) === index;
};

let replace = function(element) {
  return element.replace(/"/g, '');
};

let animals = ['"cat"', '"dog"', '"cat"', '"bird"', '"dog"'];
animals = animals.filter(unique).map(replace);
=> [ 'cat', 'dog', 'bird' ]
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?