How to use Array.prototype.splice() Method In Javascript
- 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.
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");
}
Output
arrayA = [ { name: 'Rohit' }, { name: 'Rahul' } ] arrayB = [ { name: 'Pratik' }, { name: 'Mahesh' } ]
How to Swap Two Array of Objects Values using JavaScript ?
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.