Reputation: 69
I have 2 arrays as shown, now I want the less data array (specifically 2) to have the same amount as the 2 arrays above (23), how should I handle it?
The result I want should look something like this
[1,2,3,4,5,6,7,8,9,10]
["","","","",5,6,7,8,9,10]
thanks for help
Upvotes: 0
Views: 88
Reputation: 122916
A simple loop should do the trick
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = [5, 6, 7, 8, 9, 10];
while (arr2.length < arr1.length) {
arr2.unshift("");
}
console.log(`arr1.length: ${arr1.length}, arr2.length: ${arr2.length}\n${
JSON.stringify(arr1)}\n${JSON.stringify(arr2)}`);
// more generic
// a function to compare lengths of 2 arrays and insert spaces into
// the shortest array until its length equals the longest
const makeEqualLength = (arr1, arr2, clone) => {
[arr1, arr2] = clone ? [arr1.slice(), arr2.slice()] : [arr1, arr2];
const [longer, shorter] = arr1.length < arr2.length ? [arr2, arr1] : [arr1, arr2];
while(shorter.length < longer.length) {
shorter.unshift("");
}
return [arr1, arr2];
};
arr1 = [...Array(10)].map(() => Math.floor(Math.random() * 42));
arr2 = [...Array(3)].map(() => Math.floor(Math.random() * 42));
const [newArr1, newArr2] = makeEqualLength(arr1, arr2, true);
// └─ use function │
// └─ original arrays unchanged
console.log(`newArr1.length: ${newArr1.length}, newArr2.length: ${newArr2.length}\n${
JSON.stringify(newArr1)}\n${JSON.stringify(newArr2)}`);
Upvotes: 2
Reputation: 15083
You can create a new array and merge the two arrays
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = [5, 6, 7, 8, 9, 10];
arr2 = [...Array(arr1.length - arr2.length).fill(""), ...arr2]
console.log(`arr1.length: ${arr1.length}, arr2.length: ${arr2.length}\n${
JSON.stringify(arr1)}\n${JSON.stringify(arr2)}`);
Upvotes: 1
Reputation: 471
If you want to fill the start of the array, maybe the following would help you out:
Array(array1.length - array2.length).fill('').concat(array2);
Please answer if you need more help than this as your question is not a 100% clear now.
Upvotes: 1
Reputation: 1074475
You can insert entries into an array via splice
:
const diff = bigger.length - smaller.length;
if (diff > 0) {
smaller.splice(0, 0, ...Array(diff).fill(""));
}
Live Example:
const bigger = [1,2,3,4,5,6,7,8,9,10];
const smaller = ["y", "z"];
const diff = bigger.length - smaller.length;
if (diff > 0) {
smaller.splice(0, 0, ...Array(diff).fill(""));
}
console.log("Result:");
console.log(JSON.stringify(bigger));
console.log(JSON.stringify(smaller));
Or create a new array with the necessary additional entries:
const diff = bigger.length - smaller.length;
if (diff > 0) {
smaller = [...Array(diff).fill(""), ...smaller];
}
Live Example:
const bigger = [1,2,3,4,5,6,7,8,9,10];
let smaller = ["y", "z"];
const diff = bigger.length - smaller.length;
if (diff > 0) {
smaller = [...Array(diff).fill(""), ...smaller];
}
console.log("Result:");
console.log(JSON.stringify(bigger));
console.log(JSON.stringify(smaller));
Upvotes: 2