// 並び替えの基準となる配列
const baseArray: string[] = ["apple", "banana", "cherry", "date"];
// 並び替えたい配列 (基準配列より要素数が少ない)
const targetArray: string[] = ["cherry", "apple"];
// baseArrayの順にtargetArrayを並び替える
const sortedArray = targetArray
.filter(item => baseArray.includes(item)) // baseArrayに存在しない要素を除外
.sort((a, b) => baseArray.indexOf(a) - baseArray.indexOf(b)); // baseArrayの順に並び替え
console.log(sortedArray);
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme