How Create more empty data in the Array? - javascript

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

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));

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)}`);

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.

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)}`);

Related

Javascript get array element from the condition of summation of array element

I have an Array, arr = [2,4,8,7,3,6] I want to make each element of it be summation when the result is 10 , then save the element it would be arranged to another array.
make the element that result is 10 close each other like 2 and 8, add to another element named arr2.
result i need : arr2[2,8,3,7,4,6]
my code :
const arr = [2, 4, 8, 7, 3, 6];
let arr2 = [];
for (let i = 0; i < arr.length(); i++) {
let Number1 = arr[i];
let Number2 = arr[(i + 1)];
if (Number1 + Number2 === 10) {
let element1 = arr.indexOf(Number1);
let element2 = arr.indexOf(Number2);
arr2.push(element1, element2);
}
console.log(arr2[i]);
}
someone can solve my problem please ?
If you need to create arr2 so that the items sum up to 10 you can make use of a simple map here:
const arr = [2, 4, 8, 7, 3, 6];
const arr2 = arr.map((item) => 10 - item)
console.log(arr2);
You should first loop through the array to create a dictionary of value to index, then loop the array again and lookup for the complement of the current value to the target. If it exist then yes you got the answer.
.filter(x => x > i) is to search for complement that has higher index than current one so that we will not get duplicated result pushed. For example input is [2, 8], you don't want to get [2, 8, 8, 2]
Here is my solution
const arr = [2, 4, 8, 7, 3, 6];
let arr2 = [];
function solution(target: number, input: number[]): number[] {
const result: number[] = [];
const lookUpMap: {[key: number]: number[]} = {};
let i = 0;
for (const each of input) {
if (!(each in lookUpMap)) {
lookUpMap[each] = [];
}
lookUpMap[each].push(i);
i++;
}
i = 0;
for (const each of input) {
const difference = target - each;
if (difference in lookUpMap) {
const complementIndex = lookUpMap[difference].filter(x => x > i)[0];
if (complementIndex) {
result.push(input[i], input[complimentingIndex]);
}
}
i++;
}
return result;
}
arr2 = solution(10, arr);
console.log(arr2);
Assuming a valid result can be created for the given arr. A fairly simple solution would be to sort the array first. Then step through half the array and take the element on the current index, and the element on the inverse index (length - 1 - index). And push() those both in the resulting array.
So here in steps, given you have the following array:
[2, 4, 8, 7, 3, 6]
You sort it:
[2, 3, 4, 6, 7, 8]
Then you step through half the indexes and take each element, and the element on the inverse index.
[2, 3, 4, 6, 7, 8]
// \ \ \/ / /
// \ ------ / -> [2, 8, 3, 7, 4, 6]
// ----------
const arr = [2, 4, 8, 7, 3, 6];
const sortedArr = Array.from(arr).sort((a, b) => a - b); // ascending
const length = sortedArr.length;
const nPairs = length / 2;
const arr2 = [];
for (let i = 0; i < nPairs; ++i) {
arr2.push(
sortedArr[i],
sortedArr[length - 1 - i],
);
}
// or if you want a more functional approach:
// const arr2 = Array.from({ length: nPairs }).flatMap((_, i) => [sortedArr[i], sortedArr[length - 1 - i]]);
console.log(arr2);
Do note that this is probably not the fastest solution, because sorting is non-linear.
Obviously this solution does not work if an invalid input is given, like [7,2,1,8] which can never produce a valid output.

Check how many times a value in an array appears in another array

I am trying to see how many times a value in one array appears in another. This was one thing I but it didn't work.
arr1 = [1, 2, 3, 4, 5];
arr2 = [1, 7, 8, 9, 10];
count = 0;
for (x in arr2){
for (y in arr1){
if (x == y){
count +=1;
}
}
}
console.log(count);
Another thing i tried was this.
(arr1.some((val)=>{return arr2.includes(val);} ))
It checks if at least one value matches but i wasn't sure on how to implement a count for it.
My goal is to see how many times a value from arr2 appears in arr1. It should return 1 in this case.
You could use Array.prototype.reduce in combination with Array.prototype.filter in order to get an Object of repeated values
const arr1 = [1, 2, 3, 4, 5, 1, 1, 1, 9, 9]; // Repeated values
const arr2 = [1, 7, 8, 9, 10]; // Unique values
const appearances = (arrUnique, arrRepeated) => arrUnique.reduce((ob, valUnique) => {
ob[valUnique] = arrRepeated.filter(v => valUnique === v).length;
return ob;
}, {});
console.log(appearances(arr2, arr1)); // {value: counts, ...}
console.log(appearances(arr2, arr1)[1]); // 4
which will return:
{
"1": 4, // repeats 4 times
"7": 0,
"8": 0,
"9": 2, // repeats 2 times
"10": 0
}
You could take an object from the counting values, then iterate the second array and count only wanted values.
const
array1 = [1, 2, 3, 4, 5],
array2 = [1, 7, 8, 9, 10],
result = array1.reduce(
(r, v) => (v in r && r[v]++, r),
Object.fromEntries(array2.map(v => [v, 0]))
);
console.log(result);
x and y will be the indexes of the loops when using this syntax.
So get what you are after you could do it like this.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 7, 8, 9, 10];
count = 0;
for (x in arr2){
for (y in arr1){
if (arr2[x] === arr1[y]){
count +=1;
}
}
}
console.log(count);
Details are commented in the example and printed on the console. Using reduce() and Map() concept was from here.
// Utility function
const log = data => console.log(JSON.stringify(data));
log(`const arr1 = [1, 2, 3, 4, 5];`);
log(`const arr2 = [1, 7, 8, 9, 10];`);
log(`const arr3 = [1, 2, 3, 4, 5, 6, 7];`)
log(`const arr4 = [1, 7, 8, 9, 10];`);
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 7, 8, 9, 10];
const arr3 = [1, 2, 3, 4, 5, 6, 7];
const arr4 = [1, 7, 8, 9, 10];
const times = (arrA, arrB) =>
// Returns n if...
arrB.filter(n =>
// ...n exists in arrA
arrA.includes(n))
// Return how many matches
.length;
log(`#param: arr1, arr2`)
log(times(arr1, arr2));
log(`#param: arr3, arr4`)
log(times(arr3, arr4));
// ...Rest operator will accept an unlimited amount
const frequency = (...arrays) => {
// Combine params into one array
let array = [...arrays.flat()],
min;
// If the first param is a string...
if (''+array[0] === array[0]) {
/*
...remove it from the array and convert it into a number.
Otherwise it's 1
*/
min = +array.shift();
} else min = 1;
// 4. Convert Map into an array of [key, value] pairs
return [...array
.reduce((grp, val) =>
/*
3. Set [value] on Map to the it's current value +1
*/
grp.set(val,
/*
2. Get [value] from Map, but if it doesn't exist yet then it's a
zero.
*/
(grp.get(val) || 0) + 1)
// 1. Create Map object
, new Map()
)]
// 5. Return each pair that meets or exceeds min
.filter(([key, val]) => val >= min);
}
log(`#param: arr1, arr2`);
log(frequency(arr1, arr2));
log(`#param: arr3, arr4`);
log(frequency(arr3, arr4));
log(`frequency() will accept anything in unlimited amounts`);
log(`#param: arr1, arr2, arr3, arr4, 10, 8`);
log(frequency(arr1, arr2, arr3, arr4, 10, 8));
log(`Pass first parameter as a string of a number if you want a minimum count returned`);
log(`#param: '2', arr3, arr4`);
log(frequency('2', arr3, arr4));
log(`If you want use an object instead an array pairs, use Object.fromEntries(frequency(arr1, arr2))`);
log(Object.fromEntries(frequency(arr1, arr2)));
.as-console-row::after { width: 0; font-size: 0; }
.as-console-row-code { width: 100%; word-break: break-word; }
.as-console-wrapper { min-height: 100% !important; min-width: 100%; }

i want to do sum of two arrays ,and the sum have to start calculate values from right to left for both the arrays

i want to sum of two arrays where if my first array has 2 elements and 2nd array has 4 elements so the problem is it is sum the starting elements of both arrays,, but i want the
sum should be start calculating from right to left for both the arrays and if the value of each element is suppose 11 so it should remain the last 1 and the first 1 should go up with next element calculation such as my expected result is 1234+5678=6912 in new array = [6,9,1,2]
here is my code-
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
function sumArr(A1, A2) {
let A3 = [];
for (let i = 0; i < Math.max(A1.length , A2.length); i++) {
A3.push((A1[i] || 0) + (A2[i] || 0));
}
return A3;
}
console.log(sumArr(Arr1, Arr2))
I'm not sure if I got the question right
But here a more generic function that I hope does what you are expecting to
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const Arr3 = [9, 10]
//more general with
const sumArray = (...arr) => {
const length = Math.max(...arr.map(a => a.length))
return Array(length)
.fill(0)
.map((_, i) => {
return arr.reduce((sum, a) => sum + (a[i] || 0) , 0)
})
}
console.log(sumArray(Arr1, Arr2))
console.log(sumArray(Arr1, Arr3))
console.log(sumArray(Arr1, Arr2, Arr3))
Here a different version based on #RenauldC5 response
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const Arr3 = [9, 10]
//more general with
const sumArray = (...arr) =>
arr.reduce((res, a) => res + parseInt(a.join('')), 0)
.toString()
.split('')
.map(n => parseInt(n))
console.log(sumArray(Arr1, Arr2))
console.log(sumArray(Arr1, Arr3))
console.log(sumArray(Arr1, Arr2, Arr3))
I guess the right approach would be to
Change array to number
Do the classic sum
Split the number into array
const Arr1 = [1, 2, 3, 4];
const Arr2 = [5, 6, 7, 8];
const num1 = parseInt(Arr1.join(''))
const num2 = parseInt(Arr2.join(''))
const total = num1 + num2
const Arr3 = total.toString().split('').map(x => parseInt(x))
console.log(Arr3)
This would work, but both the array should have same number of elements. If your array length is not equal, you can add 0 for the empty space and this code will work on that too.
const a1 = [1, 2, 3, 4]
const a2 = [5, 6, 7, 8]
let carry = 0
const sum = []
for(let i = a1.length-1; i >= 0; i--){
let num = a1[i] + a2[i] + carry
let numArr = num.toString().split('')
if(numArr.length > 1){
carry = Number(numArr[0])
sum.push(Number(numArr[1]))
} else{
carry = 0
sum.push(Number(numArr[0]))
}
}
sum.reverse()
console.log(sum)

Trying to merge two unsorted arrays in Javascript

I have written code in javascript trying to return a single sorted array by giving two sortedarray inputs.
function finalArray(arr1, arr2) {
const mergedArray = [];
if (arr1.length === 0) {
return arr2;
}
if (arr2.length === 0) {
return arr1;
}
let arr1Item = arr1[0];
let arr2Item = arr2[0];
let i = 1;
let j = 1;
while (arr1Item || arr2Item) {
if (arr2Item === undefined || arr1Item < arr2Item) {
mergedArray.push(arr1Item);
arr1Item = arr1[i];
i++;
} else {
mergedArray.push(arr2Item);
arr2Item = arr2[j];
j++;
}
}
return mergedArray
}
console.log(finalArray([2, 6, 4, 10], [15, 1, 5, 33]));
Can anyone help with how to merge unsorted arrays?
Merge your two arrays first, then perform the sort?
const arr1 = [2, 6, 4, 10];
const arr2 = [10, 1, 5, 33];
const newArray = ([...arr1, ...arr2]);
newArray.sort(function(a,b){return a - b});
console.log(newArray);
Expected output: [1, 2, 4, 5, 6, 10, 10, 33]
The problem is you are comparing every two pair of data and pushing smaller one.
First try to sort each sub array without entering compare process for mixing.
After the sub arrays are being sorted, then compare to each other.

issue with merge sorted arrays problem using javascript

I am trying to solve merge 2 sorted arrays problem using javascript. Please find my solution below:
input:
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
output:
[1, 2, 3, 4, 7, 8, 9 10]
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 || arrayItem1) {
arrayItem1 = arrayItem1 === undefined ? 0 : arrayItem1;
arrayItem2 = arrayItem2 === undefined ? 0 : arrayItem2;
if (arrayItem1 < arrayItem2) {
console.log('inside if');
console.log("first array", arrayItem1);
arrayItem1 = arr1[i];
i++;
mergedArray.push(arrayItem1);
} else {
console.log('inside else');
console.log("second array", arrayItem2);
arrayItem2 = arr2[j];
j++;
mergedArray.push(arrayItem2);
}
console.log("== merged array ==", mergedArray);
}
But it is going in infinite loop. Not sure where I am going wrong. Need a watchful pair of eyes here.
thanks
You need to check the index with the lengths of the arrays and add a final check for getting the rest of the arrays added to the merged array.
const
array1 = [1, 4, 7, 8, 10],
array2 = [2, 3, 9],
mergedArray = [];
let i = 0,
j = 0;
while (i < array1.length && j < array2.length) {
if (array1[i] < array2[j]) {
mergedArray.push(array1[i++]);
} else {
mergedArray.push(array2[j++]);
}
}
if (i < array1.length) mergedArray.push(...array1.slice(i));
if (j < array2.length) mergedArray.push(...array2.slice(j));
console.log(...mergedArray);
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
const mergedArrays = [...arr1, ...arr2];
// WITH SORT
const result = mergedArrays.sort((a, b) => Number(a) - Number(b));
console.log(result);
// WITHOUT SORT
const bubbleSort = (arr) => {
let done = false;
while (!done) {
done = true;
arr.forEach((el, i) => {
if (arr[i - 1] > arr[i]) {
done = false;
const tmp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = tmp;
}
});
}
return arr;
};
const result2 = bubbleSort(mergedArrays)
console.log(result2)
You don't really need to go through all that trouble, you can merge your arrays by destructuring your arrays in new one and just use the Array.sort() method.
UPDATE:
Added sorting without using using Array.sort(), using a sorting algorithm Bubble sort
This will also work for non positive numbers
//[1, 2, 3, 4, 7, 8, 9 10]
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 !== undefined || arrayItem1 !== undefined) {
if (arrayItem2 === undefined || arrayItem1 < arrayItem2) {
mergedArray.push(arrayItem1);
arrayItem1 = arr1[i];
i++;
} else {
mergedArray.push(arrayItem2);
arrayItem2 = arr2[j];
j++;
}
console.log('Merged array: ' + mergedArray)
}
Some issues:
The actions in the if block (and else block) occur in the wrong order. You first want to push the item, then increment the index, and then get the next value from the array so it will be used in the next comparison.
Don't assign the value 0 when a value is undefined. Just leave it undefined, otherwise you risk to push a 0 into the result that was never there in the input.
So:
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 || arrayItem1) {
if (arrayItem2 === undefined || arrayItem1 < arrayItem2) {
mergedArray.push(arrayItem1);
i++;
arrayItem1 = arr1[i];
} else {
mergedArray.push(arrayItem2);
j++;
arrayItem2 = arr2[j];
}
}
console.log("== merged array ==", mergedArray);
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
var children = arr1.concat(arr2);
console.log (children.sort(function(a, b){return a - b}));
children.sort(function(a, b){return a - b});
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
var children = arr1.concat(arr2);
console.log (children.sort(function(a, b){return a - b}));

Categories

Resources