LoginSignup
0
0

More than 3 years have passed since last update.

配列の間に特定要素を挿入するコード(javascript)

Posted at

コード

const data = [1, 2, 3];
const separater = 0;

const result = data.map((item, index)=>{
  return [index * 2, item]
}).concat(
  Array.from({length: data.length - 1})
  .map((_, index) => [index * 2 + 1, separater])
).sort()
.map(tuple=>tuple[1]);

console.log(result);
// [ 1, 0, 2, 0, 3 ]

解説

1. データに偶数インデックスを貼ります

data.map((item, index)=>{
  return [index * 2, item]
})

2. 奇数インデックスを貼った挿入データの配列を作ります

  Array.from({length: data.length - 1})
  .map((_, index) => [index * 2 + 1, separater])

3. 1-2を結合してソートをかけて値だけ抜いてきます

const result = data.map((item, index)=>{
  return [index * 2, item]
}).concat(
  Array.from({length: data.length - 1})
  .map((_, index) => [index * 2 + 1, separater])
).sort()
.map(tuple=>tuple[1]);

用途

Reactで要素の間に<hr/>要素を挟み込みたかったので作りました

0
0
1

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