LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】自分なりのワンライナー(配列操作)

Last updated at Posted at 2020-09-20

元記事はこちらになります。

ワンライナーで行こう!(JavaScriptで配列操作いろいろ)
https://qiita.com/snst-lab/items/cf1fe64cfad70838ee93

こちらで気になったものを自分なりに。
1年以上前の記事に今更かもしれませんが…

重複の削除はfilter使うよりArray.form(new Set(arr))が良いという記事はあちこちで見るので割愛。

startからendまでの連続した数値配列を生成する

2行目だけ見て書いたら、1行目がほぼ同じだったので削除

配列の中身を結合した文字列を作る

const string = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].join('');

console.log( string );      //'0123456789'

元記事では正規表現でreplaceしてたのがきになりました。

隣り合うN個の要素をまとめた配列の配列を作る(N=3)

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const wrapInArray = (arr, n) => 
    Array(Math.floor(arr.length/n)).fill().map( (_, i) => arr.slice(i*n, i*n+n) );

console.log ( wrapInArray(array, 3) );      //[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
console.log ( wrapInArray(array, 2) );      //[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

N個未満になる配列も残したい時は、Math.floor()ではなくMath.ceil()に変更

const wrapInArray = (arr, n) => 
    Array(Math.ceil(arr.length/n)).fill().map( (_, i) => arr.slice(i*n, i*n+n) );

まとめ

Array(n).fill().map((_, i)) => {...});を使いたいだけの記事でした。

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