LoginSignup
0
1

More than 5 years have passed since last update.

js 配列から目的の要素を取り除く

Last updated at Posted at 2016-12-21

お題

配列から目的の要素を取り除く。

script.js
function removeElementFromArray(arr) {
//write your code.
 }
removeElementFromArray([1, 2, 3, 1, 2, 3], 2, 3);

出力結果 

script.js
([1, 2, 3, 1, 2, 3], 2, 3) //[1, 1]
([3, 5, 1, 2, 2], 2, 3, 5) //[1]
([2, 3, 2, 3], 2, 3) //[]
(["tree", "hamburger", 53,1,2], "tree", 53 ,2) //["hamburger", 1 ]

使ったもの

slice()
filter()
splice()
arguments

思考の流れ

・配列から要素を取り除くにはfilter()が使えそう
→filter()の条件をどのように設定したらよいだろう?
→removeElementFromArrayの引数の配列に続く値(2,3)を取得できたら条件に設定できそうだ、、、

→配列と続く値の扱いに手こずる。なにかないかと調べる。

→"複数の文字列を連結する関数を定義する"Array.prototype.slice.call(arguments)を探し当てる。
入力してみると[[1, 2, 3, 1, 2, 3], 2, 3]が返ってくる!

→splice(0,1)で最初の配列を除いて変数にいれる。
  配列に続く値(2,3)の取得ができた。

→filter()の条件の設定方法を考える。
→indexOf()で−1となる値(2,3に対して誤)を返るようにする。

結果、[1,1]の取得ができました。

実行したコード

script.js
function removeElementFromArray(arr) {
  var args = Array.prototype.slice.call(arguments); //args [[1, 2, 3, 1, 2, 3], 2, 3]
  args.splice(0, 1); //args [2,3]
  return arr.filter(function(element) { //element 1, 2, 3, 1, 2, 3
    return args.indexOf(element) === -1; 
  });
}
removeElementFromArray([1, 2, 3, 1, 2, 3], 2, 3);

他にもコードが浮かんだ方、コメントお待ちしてます。

0
1
2

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
0
1