In-place sorting
By implementing an in-place sorting algorithm that moves the duplicate elements to the beginning of the array. The function iterates through the array, identifying duplicate objects based on their property, and shifts them to the first occurrence in the array while maintaining the relative order of other elements. Finally, it returns the modified array.
Syntax:
Interface:
interface MyObject {
key1: type1;
key2: type2;
key3: type3;
}
Function:
function Demo(arr: MyObject[]): MyObject[] {}
Example: A function utilizing the nested loops to iterate through an array, identifying duplicates, and swapping them with the following object based on a specific property comparison for a more efficient data arrangement.
interface MyObject {
id: number;
name: string;
}
function moveDuplicatesToFirstIndex(arr: MyObject[]):
MyObject[] {
let currentIndex = 0;
while (currentIndex < arr.length) {
const currentObj = arr[currentIndex];
let nextIndex = currentIndex + 1;
while (nextIndex < arr.length) {
const nextObj = arr[nextIndex];
if (currentObj.id === nextObj.id) {
const temp = arr[currentIndex + 1];
arr[currentIndex + 1] = arr[nextIndex];
arr[nextIndex] = temp;
currentIndex++;
}
nextIndex++;
}
currentIndex++;
}
return arr;
}
const myArray: MyObject[] = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "John" },
{ id: 4, name: "Doe" },
{ id: 5, name: "Jane" },
{ id: 1, name: "John" }
];
const modifiedArray =
moveDuplicatesToFirstIndex(myArray);
console.log(modifiedArray);
Output:
[{
"id": 1,
"name": "John"
}, {
"id": 1,
"name": "John"
}, {
"id": 3,
"name": "John"
}, {
"id": 4,
"name": "Doe"
}, {
"id": 5,
"name": "Jane"
}, {
"id": 2,
"name": "Jane"
}]
Time Complexity: O(n^2)- because it uses nested loops. However, the space complexity remains constant, making it efficient in terms of memory usage.
Space Complexity: O(1)- because it doesn’t require any extra space proportional to the input size making it efficient in terms of memory usage.
How to move Duplicate to First Index in an Array of Objects in TypeScript ?
To efficiently rearrange an array of objects in TypeScript, moving duplicates to the first index, The approach is first to identify the duplicate within the array, then to remove the duplicate from its current position in the array then at last to re-insert the duplicate at the first index of the array.
There are several ways to move the duplicate to the first index in an array of Objects in TypeSCript which are as follows:
Table of Content
- Shifting Duplicates
- In-place sorting
- Using reduce method