Open In App

How to move Duplicate to First Index in an Array of Objects in TypeScript ?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads