Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save discoNeko/3d636758358873a7952f499eb2a49fd2 to your computer and use it in GitHub Desktop.
Save discoNeko/3d636758358873a7952f499eb2a49fd2 to your computer and use it in GitHub Desktop.
// 1.昇順の順番に沿って挿入する
const a = [11, 22, 33, 44, 55, 66, 77, 88, 99]
let b = 50
let index = a.findIndex(v => v > b)
index < 0 ? a.push(b) : a.splice(index, 0, b)
console.log(a)
// output:
// > Array [11, 22, 33, 44, 50, 55, 66, 77, 88, 99]
// 2.最大の場合
b = 500
index = a.findIndex(v => v > b)
index < 0 ? a.push(b) : a.splice(index, 0, b)
console.log(a)
// output:
// > Array [11, 22, 33, 44, 50, 55, 66, 77, 88, 99, 500]
// 3.最小の場合
b = 5
index = a.findIndex(v => v > b)
index < 0 ? a.push(b) : a.splice(index, 0, b)
console.log(a)
// output:
// > Array [5, 11, 22, 33, 44, 50, 55, 66, 77, 88, 99, 500]
// 4.挿入先が空配列の場合
a.length = 0
console.log(a)
// output:
// > Array []
b = 50
index = a.findIndex(v => v > b)
index < 0 ? a.push(b) : a.splice(index, 0, b)
console.log(a)
// output:
// > Array [50]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment