LoginSignup
2

More than 5 years have passed since last update.

js 配列の要素を欠落させる

Posted at

お題

第一引数の配列の要素を第二引数の関数がtrueになるまで先頭から欠落させる。
例 
([1, 2, 3, 4], function(n) {return n >= 3;})の場合、
配列の要素の先頭が3になるときまで、要素を欠落させる。

function dropElements(arr, func) {
  // write your code.
}
dropElements([1, 2, 3, 4], function(n) {return n >= 3;});//[3, 4]

出力結果 例

dropElements([0, 1, 0, 1], function(n) {return n === 1;})// [1, 0, 1]
dropElements([1, 2, 3], function(n) {return n > 0;})// [1, 2, 3]
dropElements([1, 2, 3, 4], function(n) {return n > 5;})// []
dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})// [7, 4]
dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})// [3, 9, 2]

つかったもの

for文
if文
shift()

考え方

・for文で第二引数がtrueになるまで配列にshift()の処理を繰り返す。

コード

function dropElements(arr, func) {
  var times = arr.length;
  for (var i = 0; i < times; i++) {
    if (func(arr[0])) {
      break;
    } else {
      arr.shift();
    }
  }
  return arr;
}
dropElements([1, 2, 3, 4], function(n) {return n >= 3;});

ES6

function dropElements(arr, func) {
  return arr.slice(arr.findIndex(func) >= 0 ? arr.findIndex(func): arr.length, arr.length);
}
dropElements([1, 2, 3, 4], function(n) {return n >= 3;});

findIndex()

while文のコード

function dropElements(arr, func) {
  while(arr.length > 0 && !func(arr[0])) {
    arr.shift();
  }
  return arr;
}
dropElements([1, 2, 3, 4], function(n) {return n >= 3;});

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

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