How to move Duplicate to First Index in an Array of Objects in TypeScript ?
Last Updated :
15 May, 2024
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:
Shifting Duplicates
This approach provides an efficient solution for reordering arrays with duplicate elements, ensuring that duplicates are positioned at the beginning while maintaining the order of non-duplicate elements. You can move duplicate objects to the first index in an array of objects in TypeScript by iterating through the array and shifting duplicate objects to the first index.
Syntax:
Interface:
interface MyObject {
key1: type1;
key2: type2;
key3: type3;
}
Function:
function Demo(arr: MyObject[]): MyObject[] {}
Example: To demonstrate moving duplicate using a function that processes an array of objects, identifying duplicates, and relocates them to the first index for a more organized data structure.
JavaScript
interface MyObject {
id: number;
name: string;
}
function moveDuplicatesToFirstIndex(arr: MyObject[]):
MyObject[] {
const map = new Map < number, number> ();
for (let i = 0; i < arr.length; i++) {
const obj = arr[i];
if (map.has(obj.id)) {
const index = map.get(obj.id)!;
arr.splice(index, 0, arr.splice(i, 1)[0]);
} else {
map.set(obj.id, i);
}
}
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": 2,
"name": "Jane"
}, {
"id": 3,
"name": "John"
}, {
"id": 4,
"name": "Doe"
}, {
"id": 5,
"name": "Jane"
}]
Time Complexity: O(N), where n is the number of elements in the array. For each element, we perform operations such as map.has(), map.get(), splice(), and map.set(), each of which generally takes O(1) time complexity.
Space Complexity: O(N) -We use a Map data structure to keep track of the indices of each elements. The space required for the map depends on the number of unique elements in the array. In the worst case, where all elements are unique, the space complexity would be O(n) to store all the indices in the map. Apart from the input array and the Map, the function uses a constant amount of additional space for variables like obj, index, etc., which doesn't grow with the size of the input.
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.
JavaScript
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.
Using reduce method
We can also achieve the desired outcome using the reduce method in our approach. The function will utilize an object for efficient lookup and iterate through the array, pushing non-duplicate elements to the output array and moving duplicates to the first index. Finally, it will log the result to the console.
Syntax:
Function:
function Demo(arr: MyObject[]): MyObject[] {}
unshift
The Array.unshift() is an inbuilt TypeScript function that is used to add one or more elements to the beginning of an array.
array.unshift( element1, ..., elementN )
reduce
The Array.reduce() is an inbuilt TypeScript function which is used to apply a function against two values of the array as to reduce it to a single value.
array.reduce(callback[, initialValue])
Example: This code utilizes an object to efficiently identify and remove duplicate objects from an array based on a unique key composed of the object's id and name properties. The resulting array maintains distinct elements with duplicates shifted to the first index.
JavaScript
const arrayOfObjects = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Doe' },
{ id: 3, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 4, name: 'Alice' },
{ id: 5, name: 'Bob' },
{ id: 2, name: 'Doe' }
];
function moveDuplicatesToFirstIndex(arr: any[]): any[] {
const seen: { [key: string]: boolean } = {};
return arr.reduce((acc: any[], obj: any) => {
const key = `${obj.id}-${obj.name}`;
if (!(key in seen)) {
seen[key] = true;
acc.push(obj);
} else {
acc.unshift(obj);
}
return acc;
}, []);
}
const result = moveDuplicatesToFirstIndex(arrayOfObjects);
console.log(result);
Output:
[{
"id": 2,
"name": "Doe"
}, {
"id": 1,
"name": "John"
}, {
"id": 1,
"name": "John"
}, {
"id": 2,
"name": "Doe"
}, {
"id": 3,
"name": "Jane"
}, {
"id": 4,
"name": "Alice"
}, {
"id": 5,
"name": "Bob"
}]
Time Complexity: O(n) - Since we iterate through the array once.
Space Complexity: O(n) - As we create a new array to store the result, and also use an object to keep track of seen keys. However, the space used by the object is bounded by the number of unique keys in the array.
Two-Pass Algorithm with Map
This approach involves two passes through the array. In the first pass, we identify duplicates and store them in a separate list while maintaining their order. In the second pass, we rebuild the array with duplicates at the front, followed by the remaining unique elements.
JavaScript
interface MyObject {
id: number;
name: string;
}
function moveDuplicatesToFirstIndex(arr: MyObject[]): MyObject[] {
const map = new Map<number, number>();
const duplicates: MyObject[] = [];
const uniqueElements: MyObject[] = [];
// First pass: Identify duplicates and separate them
for (const obj of arr) {
if (map.has(obj.id)) {
duplicates.push(obj);
} else {
map.set(obj.id, 1);
uniqueElements.push(obj);
}
}
// Combine duplicates at the front followed by unique elements
return [...duplicates, ...uniqueElements];
}
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": 2,
"name": "Jane"
}, {
"id": 3,
"name": "John"
}, {
"id": 4,
"name": "Doe"
}, {
"id": 5,
"name": "Jane"
}]
Similar Reads
How to Convert an Array of Objects into Object in TypeScript ?
Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript. We are given an array of objects
3 min read
How to Remove Duplicates from an Array of Objects using TypeScript ?
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is. Examples of Removing Duplicates from an Array of Objects using TypeScript Table of Content Using filter() and
4 min read
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
6 min read
How to Check if an Array Includes an Object in TypeScript ?
In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method. There are several ways to check if an array includes an object
3 min read
How to find the Total Number of Elements in an Array in TypeScript ?
In TypeScript, arrays are a common data structure used to store collections of elements. You can store multiple elements of different or the same data type inside them by explicitly typing. The below methods can be used to accomplish this task: Table of Content Using the length property Using the fo
3 min read
How to Iterate Array of Objects in TypeScript ?
In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
4 min read
How to Cast a JSON Object Inside of TypeScript Class ?
Casting a JSON object to a TypeScript class involves converting a plain JSON object (which lacks methods and proper typing) into an instance of a class that includes all the defined methods and type safety of that class. Types of Objects in TypeScriptPlain Objects: When parsing JSON data using the J
3 min read
How to Create a Typed Array from an Object with Keys in TypeScript?
Creating a typed array from the keys of an object in TypeScript ensures that your application maintains type safety, particularly when interacting with object properties. Here we'll explore different approaches to achieve this using TypeScript's built-in Object methods. Below are the approaches used
3 min read
How to Remove Duplicates from an Array of Objects in JavaScript?
Here are some effective methods to remove duplicates from an array of objects in JavaScript 1. Using filter() and findIndex() Methods - Most UsedThe simplest way to remove duplicates is by using filter() and findIndex(). This method keeps the first occurrence of each object with a unique property (l
3 min read
How to Cast Object to Interface in TypeScript ?
In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
3 min read