2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列並び替え

Posted at
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);
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?