How to Swap Two Array of Objects Values using JavaScript ?
Last Updated :
17 Jul, 2024
Swapping values between two arrays of objects is a common operation in JavaScript, there are multiple methods to swap values between arrays of objects efficiently. Swapping values between arrays can be useful in scenarios like reordering data, shuffling items, or performing certain algorithms.
These are the following approaches:
Using a Temporary Variable
swapping values between two arrays of objects using a temporary variable involves the following steps:
- Create a temporary variable to store the value of the array during the swap.
- Assign the value of the first array of object to the temporary variable.
- Assign the value of the second array of object to the position originally held by the first array of object.
- Assign the value stored in the temporary variable to the position held by the second array of object.
- Repeat the assignments for each corresponding pair of object in the arrays.
- After completing the swap for all object in the arrays, return 'true' to indicate that the swapping was successful.
Example: This example shows the implementation of the above-explained approach.
JavaScript
function fun(arrayA, arrayB) {
// Arrays must have the same length
if (arrayA.length !== arrayB.length) {
return false;
}
for (let i = 0; i < arrayA.length; i++) {
let tempVariable = arrayA[i];
arrayA[i] = arrayB[i];
arrayB[i] = tempVariable;
}
// Swapping arrays successful
return true;
}
let arrayA = [{ name: "geek" },
{ name: "geek3" }];
let arrayB = [{ name: "geek1" },
{ name: "geek7" }];
let result = fun(arrayA, arrayB);
if (result) {
console.log(arrayA);
console.log(arrayB);
}
else {
console.log("The length of an array must be the same");
}
Output[ { name: 'geek1' }, { name: 'geek7' } ]
[ { name: 'geek' }, { name: 'geek3' } ]
Using Destructuring Assignment
swapping values between two arrays of objects using a destructuring assignment involves the following steps:
- Use array destructuring assignment to simultanously extract elements from both arrays into variables
- The elements from 'arrayA' are assigned to 'arrayB' and vice versa.
- Repeate this destructuring assignment for each pair of correspoding element in the array.
- After completing the swap for all object in the arrays, return 'true' to indicating that the swapping was successful.
Syntax:
[arrayA[i], arrayB[i]] = [arrayB[i], arrayA[i]];
Example: This example shows the implementation of the above-explained approach.
JavaScript
function swapArraysUsingDestructuring(arrayA, arrayB) {
// Arrays must have the same length
if (arrayA.length !== arrayB.length) {
return false;
}
for (let i = 0; i < arrayA.length; i++) {
[arrayA[i], arrayB[i]] = [arrayB[i], arrayA[i]];
}
// Swapping arrays successful
return true;
}
let arrayA = [1, 2, 3];
let arrayB = [5, 6, 7];
let result = swapArraysUsingDestructuring(arrayA, arrayB);
if (result) {
console.log(`Array A: ${arrayA}`); //Output -> arrayA = [5, 6, 7]
console.log(`Array B: ${arrayB}`);//Output -> arrayB = [1, 2, 3]
}
else {
console.log("The length of an array must be the same");
}
OutputArray A: 5,6,7
Array B: 1,2,3
Using Array.prototype.splice() Method
- Use the Splice() method to remove element from one array and insert them into another array at specified position (index).
- Repeat this splicing operation for each pair of corresponding elelment in the arrays.
- After completing the swap for all object in the arrays, return 'true' to indicating that the swapping was successful.
Syntax:
arrayA.splice(i, 1, ...arrayB.splice(i, 1, arrayA[i])[0]);
Example: This example shows the implementation of the above-explained approach.
JavaScript
function fun(arrayA, arrayB) {
// Arrays must have the same length
if (arrayA.length !== arrayB.length) {
return false;
}
for (let i = 0; i < arrayA.length; i++) {
arrayA.splice(i, 1, arrayB.splice(i, 1,
arrayA[i])[0]);
}
// Swapping arrays successful
return true;
}
let arrayA = [{ name: "Pratik" },
{ name: "Mahesh" }];
let arrayB = [{ name: "Rohit" },
{ name: "Rahul" }];
let result = fun(arrayA, arrayB);
if (result) {
console.log("arrayA =", arrayA);
console.log("arrayB =", arrayB);
}
else {
console.log("The length of an array must be the same");
}
OutputarrayA = [ { name: 'Rohit' }, { name: 'Rahul' } ]
arrayB = [ { name: 'Pratik' }, { name: 'Mahesh' } ]
Using Object.assign and Spread Operator:
You can swap values between objects in arrays using Object.assign and the spread operator. Create new arrays with swapped values by merging objects with Object.assign and spreading the remaining elements using the spread operator for efficient swapping.
Example: In this example we are swaping the name values between the first objects in array1 and array2 by creating new arrays with updated first objects while keeping the rest of the elements unchanged.
JavaScript
let array1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
let array2 = [{ id: 3, name: 'Alice' }, { id: 4, name: 'Bob' }];
// Swap the name values between the first objects in array1 and array2
array1 = [{ ...array2[0], name: array1[0].name }, ...array1.slice(1)];
array2 = [{ ...array1[0], name: array2[0].name }, ...array2.slice(1)];
console.log(array1);
console.log(array2);
Output[ { id: 3, name: 'John' }, { id: 2, name: 'Jane' } ]
[ { id: 3, name: 'Alice' }, { id: 4, name: 'Bob' } ]
Using the map Method
You can use the map method to swap values between two arrays of objects by creating new arrays with swapped values. This method ensures a clean and functional approach to swapping elements without mutating the original arrays directly.
Example:
JavaScript
function swapUsingMap(arr1, arr2) {
const swappedArr1 = arr1.map((item, index) => ({ ...arr2[index] }));
const swappedArr2 = arr2.map((item, index) => ({ ...arr1[index] }));
return [swappedArr1, swappedArr2];
}
let array1 = [{ name: 'Alice' }, { name: 'Bob' }];
let array2 = [{ name: 'Charlie' }, { name: 'David' }];
let [newArray1, newArray2] = swapUsingMap(array1, array2);
console.log(newArray1); // [{ name: 'Charlie' }, { name: 'David' }]
console.log(newArray2); // [{ name: 'Alice' }, { name: 'Bob' }]
Output[ { name: 'Charlie' }, { name: 'David' } ]
[ { name: 'Alice' }, { name: 'Bob' } ]
Using the forEach Method
Swapping values between two arrays of objects using the forEach method involves iterating over each element of the arrays and swapping the corresponding objects. This approach provides a straightforward and readable way to swap values.
Steps:
- Ensure the arrays have the same length.
- Use the forEach method to iterate over the elements of the arrays.
- For each iteration, swap the corresponding elements between the arrays.
- After completing the swap for all objects in the arrays, return true to indicate that the swapping was successful.
Example:
JavaScript
function swapUsingForEach(arrayA, arrayB) {
// Arrays must have the same length
if (arrayA.length !== arrayB.length) {
return false;
}
arrayA.forEach((item, index) => {
const temp = arrayA[index];
arrayA[index] = arrayB[index];
arrayB[index] = temp;
});
// Swapping arrays successful
return true;
}
let arrayA = [{ name: "Alpha" }, { name: "Beta" }];
let arrayB = [{ name: "Gamma" }, { name: "Delta" }];
let result = swapUsingForEach(arrayA, arrayB);
if (result) {
console.log(arrayA); // Output: [{ name: 'Gamma' }, { name: 'Delta' }]
console.log(arrayB); // Output: [{ name: 'Alpha' }, { name: 'Beta' }]
} else {
console.log("The length of an array must be the same");
}
Output[ { name: 'Gamma' }, { name: 'Delta' } ]
[ { name: 'Alpha' }, { name: 'Beta' } ]
Similar Reads
How to Swap Array Object Values in JavaScript ?
We have given the array of objects, and our task is to swap the values of the object keys present in the array of objects. Below is an example for a better understanding of the problem statement. Example:Input: arr = [{a: 1, b: 2}, {a:3, b: 4}]Output: [ { a: 2, b: 1 }, { a: 4, b: 3 } ]Explnation: Th
4 min read
How to swap key and value of JSON element using JavaScript ?
In this article, we will swap the key and value of JSON elements using JavaScript. Given a JSON object and the task is to swap the JSON object key with values and vice-versa with the help of JavaScript. Below are the following approaches: Using for loopUsing Object.keys() and ForEach() MethodUsing O
2 min read
How to map array values without using map method in JavaScript ?
Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each array element. This can also be implemented using a for loop in JavaScript. Approach 1: For this, we can create two arrays, in which
3 min read
How to add Key-Value pair to a JavaScript Object?
JavaScript object has key-value pair and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods. Below are the methods to add a key/value pair to a JavaScript object: Table of Content Using Dot NotationUsing Bracket No
3 min read
How to check two objects have same data using JavaScript ?
In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data. It is because those are two different object instances, they are
2 min read
How to remove object from array of objects using JavaScript ?
Removing an object from an array of objects in JavaScript refers to the process of eliminating a specific object from the array based on certain conditions, like matching a property value. This task is common in data manipulation, ensuring the array only contains the desired elements. There are two
2 min read
How to convert Object's array to an array using JavaScript ?
Given an array of objects and the task is to convert the object values to an array with the help of JavaScript. There are two approaches that are discussed below: Approach 1: We can use the map() method and return the values of each object which makes the array. Example: [GFGTABS] html <!DOCTYPE
2 min read
How to Sort JSON Array in JavaScript by Value ?
Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort
3 min read
How to Move a Key in an Array of Objects using JavaScript?
The JavaScript array of objects is a type of array that contains JavaScript objects as its elements. You can move or add a key to these types of arrays using the below methods in JavaScript: Table of Content Using Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce()
5 min read
How to Find & Update Values in an Array of Objects using Lodash ?
To find and update values in an array of objects using Lodash, we employ utility functions like find or findIndex to iterate over the elements. These functions facilitate targeted updates based on specific conditions, enhancing data manipulation capabilities. Table of Content Using find and assign F
4 min read