interface Item {
itemA: number;
itemB: string;
itemC: string;
}
// ソート条件を基に要素を挿入する関数
function insertSorted(arr: Item[], newItem: Item): void {
let index = 0;
while (
index < arr.length &&
(arr[index].itemA < newItem.itemA ||
(arr[index].itemA === newItem.itemA && arr[index].itemB < newItem.itemB) ||
(arr[index].itemA === newItem.itemA && arr[index].itemB === newItem.itemB && arr[index].itemC < newItem.itemC))
) {
index++;
}
arr.splice(index, 0, newItem);
}
// 2つのオブジェクト配列を作成
const array1: Item[] = [
{ itemA: 2, itemB: 'b', itemC: 'z' },
{ itemA: 1, itemB: 'a', itemC: 'x' },
{ itemA: 2, itemB: 'a', itemC: 'y' },
];
const array2: Item[] = [
{ itemA: 1, itemB: 'b', itemC: 'y' },
{ itemA: 3, itemB: 'a', itemC: 'x' },
{ itemA: 1, itemB: 'a', itemC: 'z' },
];
// 結果用の配列を作成し、array1とarray2の要素を挿入
const sortedArray: Item[] = [];
for (const item of array1) {
insertSorted(sortedArray, item);
}
for (const item of array2) {
insertSorted(sortedArray, item);
}
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