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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read