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

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.

Related

How to use javascript map to combine numbers at every nth element?

I like to combine numbers at every 4th index of an array. In the following oversimplified example, I did using "for" loop. Instead of that, I like to learn how to use "map" to achieve the same result. Thanks for any help!
function test() {
var array = [1, 2, 3, 4, 5, 6, 7, 8], arrayNew = [];
for (var n = 0; n < 4; ++n)
arrayNew[n] = array[n] + array[n + 4];
console.log(arrayNew)
}
To use .map, you could iterate the slice of the array that omits the first four elements. During that iteration, the loop index will be 4 units less, so you can grab array[i] and combine it with the currently iterated value from the slice:
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const result = array.slice(4).map((val, i) => array[i] + val);
console.log(result);
If you want to add more than just two values, but want to also add the value at 2n, 3n, ...etc, then you need a nested loop. Here .map is of less use. I would "map" with the use of Array.from, which has a callback function that performs a mapping. Secondly, the sum that has a dynamic number of terms can be performed with reduce:
function accumulate(array, n) {
const groups = Array.from({length: array.length / n});
return Array.from({length: n}, (val, i) =>
groups.reduce((sum, _, j) => sum + array[i + j*n], 0)
);
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(accumulate(array, 4));

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)

How to multiply elements of an array by elements from another array with the same index?

I am trying to write an JS algorithm in which I have two arrays.
The value of the first one will have different numerical values. The second array will be constant, say for example [5, 3, 6, 8].
Now I would like to multiply the values from the first array, by the corresponding index value from the second array, so having for example such a first array: [3, 7, 2, 5] it would look like this: 5*3, 3*7, 6*2, 8*5.
From the result I would like to create a new array, which in this case is [15, 21, 12, 40].
How can I achieve this result?
You can use map() and use the optional parameter index which is the index of the current element being processed in the array:
const arr1 = [3, 4, 5, 6];
const arr2 = [7, 8, 9, 10];
const mulArrays = (arr1, arr2) => {
return arr1.map((e, index) => e * arr2[index]);
}
console.log(mulArrays(arr1, arr2));
This is assuming both arrays are of the same length.
You can simply use for loop -
var arr1 = [5, 3, 6, 8];
var arr2 = [3, 7, 2, 5];
var finalArr = [];
for (var i = 0; i < arr1.length; i++) {
finalArr[i] = arr1[i] * arr2[i];
}
console.log(finalArr);

How Create more empty data in the Array?

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

JavaScript: Add sum of even value elements to each odd value element in an given array; show the new array

I need to write a code that adds the sum of even value elements to each odd value element in a given array and then show the new array.
Example:
array = [2,3,4,5,6,7,8,9]
Requested sum is 20. The new generated array should look like:
array = [2, 23, 4, 25, 27, 8, 29]
What I have done so far:
let oldArray = [2, 3, 4, 5, 6, 7, 8, 9];
const sumArray = arr => arr.filter(i => !(i % 2)).reduce((a, b) => a + b);
let newArray = oldArray.map (i => i%2 == 1 + sumArray);
console.log(newArray);
Take a look at this:
let array = [2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.map(x=>x%2==0?x:x+array.reduce((a,b)=> a + b*((b+1)%2) )))
It's logging an array built on the original array: if the element is even, you leave it that way. If not, you add the sum of the even numbers. How do you do this? You add the element multiplied by the rest of the division of this element added to 1 by 2.
let array = [2,3,4,5,6,7,8,9];
let newarray = [];
let sum = 0;
for(let i=0; i<array.length; i++) {
if(array[i]%2 === 0) {
sum += array[i];
}
}
for(let i=0; i<array.length; i++) {
if(array[i]%2 === 0) {
newarray.push(array[i]);
}
else {
newarray.push(array[i]+sum);
}
}

Categories

Resources