JavaScript: Using Reduce Method to Merge Together Multiple Arrays Into One Array - javascript

I have the following code below:
const intersection = (arr) => {
//console.log(arr)
return arr.reduce((a,e) => a+e, [])
}
const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));
I am expecting my code to print [5,10,15,2015,88,1,5,71,10,15,5,20] but instead it's printing 5,10,15,2015,88,1,5,71,10,15,5,20
What am I doing wrong?

You are trying to combine the arrays with the + operator. Since arrays don't support the + operator, they are casted to strings. You can use array spread or Array.concat() to combine them using Array.reduce():
const intersection = arr => arr.reduce((a, e) => [...a, ...e], [])
const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));
Or you can use Array.flat():
const intersection = arr => arr.flat();
const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));

Don't use + to add arrays. Use concat instead:
const intersection = arr => arr.reduce((a, e) => a.concat(e), []);
const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));
.as-console-wrapper { max-height: 100% !important; top: auto; }

Related

find the smallest number in a array of an array

i'm trying to write a function to find the smallest number on an array of an array.
already tryed this, but i don't really know how to do when there is arrays on an array.
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]
const min = Math.min(arr)
console.log(min)
By taking ES6, you could use the spread syntax ..., which takes an array as arguments.
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min(...arr);
console.log(min);
With ES5, you could take Function#apply, which take this and the parameters as array.
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min.apply(null, arr);
console.log(min);
For unflat arrays, take a flatten function, like
const
flat = array => array.reduce((r, a) => r.concat(Array.isArray(a) ? flat(a) : a), []),
array = [[1, 2], [3, 4]],
min = Math.min(...flat(array));
console.log(min);
You can use map to iterate over the nested arrays and then use Math.min(...array) on each to get the minimum. The output from map is an array of minimum values.
const arr = [[4, 8, 2], [7, 6, 42], [41, 77, 32, 9]];
const out = arr.map(a => Math.min(...a));
console.log(out);
Use spread ... and flat:
const a = [[0, 45, 2], [3, 6, 2], [1, 5, 9]];
console.log(Math.min(...a.flat()));
Or you might use reduce:
const arr = [[7, 45, 2], [3, 6, 2], [1, 5, 9]];
let r = arr.reduce((a, e) => Math.min(a, ...e), Infinity)
console.log(r);

JavaScript. How to Compare Input Arrays

I'm stuck with this problem for 3 days now... Someone please help me.
Challenge 5
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.
function intersection(arrayOfArrays) {
}
console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));
// should log: [5, 15]
Reduce the arrays to a Map of counts, with the value as key. Spread the Map to entries. Use Array.filter() on the Map's entries to remove all entries, which value is not equal to the arrayOfArrays lenth. Extract the original number from the entries using Array.map():
function intersection(arrayOfArrays) {
return [...arrayOfArrays.reduce((r, s) => {
s.forEach((n) => r.set(n, (r.get(n) || 0) + 1));
return r;
}, new Map())]
.filter(([k, v]) => v === arrayOfArrays.length)
.map(([k]) => k);
}
console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));
You could reduce the array by filtering with just checking if the other array contains the value.
This works for arrays with unique values.
Array#reduce:
If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.
The callback
a.filter(v => b.includes(v))
filters array a. If the array b includes the value of a, then this value v is included in the accumulator for the next iteration or as final result.
accumulator currentValue new accumulator
a b result
-------------------- -------------------- --------------------
[ 5, 10, 15, 20] [15, 88, 1, 5, 7] [ 5, 15]
[ 5, 15] [ 1, 10, 15, 5, 20] [ 5, 15]
function intersection(arrayOfArrays) {
return arrayOfArrays.reduce((a, b) => a.filter(v => b.includes(v)));
}
console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));
First try to find out the intersection of two arrays which is the base problem. Then try to build up for variable number of arrays passed as arguments for intersection. You can use reduce() for doing that.
function intersectionOfTwoArrays(arr1, arr2)
{
return arr1.filter(x => arr2.some(y => y === x));
}
function intersection(...arrayOfArrays)
{
return arrayOfArrays
.reduce((a, b) => intersectionOfTwoArrays(a, b));
}
intersection(
[5, 10, 15, 20],
[15, 88, 1, 5, 7],
[1, 10, 15, 5, 20]
);
You can go through the first array in the array of arrays and check which of its value is present in all the other arrays.
Here is an example:
function intersection(input) {
let firstArray = input[0];
let restOfArrays = input.splice(1);
return firstArray.filter(v => restOfArrays.every(arr => arr.includes(v)));
}
const input = [[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]];
const result = intersection(input);
console.log(result);
Works with even if there is duplicate in same array.. like in my example added 5 twice in arrayEle[1];
var arrayEle = [[5, 10, 15, 20], [15, 88, 1, 5, 5], [1, 10, 15, 5, 20]]
var startIndex = 1;
var newArray = [];
for (var x = 0; x < arrayEle[0].length; x++) {
var temVal = 1;
var value;
for (var y = 1; y < arrayEle.length; y++) {
for (var z = 0; z < arrayEle[y].length; z++) {
if (arrayEle[y][z] == arrayEle[0][x]) {
temVal++;
value = arrayEle[y][z];
break;
}
}
}
if (temVal == arrayEle.length) {
newArray.push(value);
console.log(value);
}
}
console.log(newArray);
//log: [5, 15]
I think you want the common elements. Let me show you how:
var Array1 = [5, 10, 15, 20]
var Array2 = [15, 88, 1, 5, 7]
var Array3 = [1, 10, 15, 5, 20]
var found = []
var Final = []
var c = 1;e = 1;
for (i = 1;i<=Array1.length;i++){
for (k = 1;k<=Array2.length;i++){
if (Array1[i] == Array2[k]){
Found[c] = Array[i];
c++;
}
}
}
for (n = 1;n <= Found.length ; n++){
for (m = 1;m <= Array3.length ; n++){
if (Found[n] == Array3[m]){
Final[e] = Found[n]
e++;
}
}
}
//the Array Final Contains 5 , 15

Combine two arrays into an array by performing an operation for each pair of values

There are two arrays having same length:
firstArray = [22, 54, 33, 10];
secondArray = [2, 27, 11, 10];
I want to get a third array as result by dividing each element of the first one to its pair in the second one, in this case the result should be:
resultArray = [11, 2, 3, 1];
I tried to do it using foreach() and map() but all I get is undefined values. For example this code:
firstArray.forEach(index) => {
resultArray[index] = firstArray[index] / secondArray[index];
});
any suggestions?
You could map the result of iteration of firstArray and take the value of secondArray with an index.
var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10],
result = firstArray.map((v , i) => v / secondArray[i]);
console.log(result);
Another solution, could be to collect all arrays in an array and reduce the data.
var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10],
result = [firstArray, secondArray].reduce((a, b) => a.map((v , i) => v / b[i]));
console.log(result);
You could try like that :
firstArray.forEach((item, index) => {
resultArray[index] = item / secondArray[index];
});
The simplest way seems to be :
var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10];
var resultArray = firstArray.map( (e, i) => e / secondArray[i]);
console.log(resultArray);
Using function reduce
var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10],
thirdArray = firstArray.reduce((a, n, i) => { a[i] = n / secondArray[i]; return a}, []);
console.log(thirdArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Get the last element of each sub-array of an array

I know that for an array it can be used last function of underscore, so in the case of this array it would be:
myArray = [32, 1, 8, 31];
lastElement = _.last(myArray);
The problem is when there is a matrix like this:
myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
and the wanted result is
lastElement = [5, 77, 2];
Any suggestions?
Use map and slice (Won't mutate the original array)
[[1, 3, 5], [55, 66, 77], [0, 1, 2]].map( s => s.slice(-1)[0] );
You can just do
var lastElement = myArray.map(_.last);
You could simply use Array.from :
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
var res = Array.from(myArray, x => x[x.length - 1]);
console.log(res);
Another possibility not already answered here would be Array#reduce :
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
var res = myArray.reduce((acc, curr) => acc.concat(curr[curr.length - 1]),[]);
console.log(res);
var lastElement = myArray.map((x) => {
return _.last(x);
});
Or you can also use ES6 map
let myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
let result = myArray.map(v => v[ v.length - 1] );
console.log(result );
Check this out. Iterate over the array using map and extract last element.
No need of any library.
let myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
let output = [];
output = myArray.map(m => m[m.length - 1] )
console.log(output)
You can use array.prototype.map to transorm each subarray to the last element in it. You can get those last elements with array.prototype.pop or arr[arr.length - 1] if you don't want to mutate myArray:
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
var lastElements = myArray.map(arr => arr.pop());
console.log(lastElements);
Perhaps loop through them with a for loop.
lastElement = [];
for (var i = 0 ; i < myArray.length ; i++) {
lastElement.push(_.last(myArray[i]));
}
Use Following Code:-
var myArray = [[1, 3, 5], [55, 66, 77], [0, 1, 2]];
lastElement = _.map(myArray, _.last);
console.log(lastElement)
// **Result is lastElement = [5, 77, 2];**
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

javascript convert elements of an array into array for themselves

How can I convert the elements of the array into another array?
let a = [2, 4, 0, 8, 9, 15]
and the result will be :
a = [[2], [4], [0], [8], [9], [15]]
Use Array#map to iterate the array, and wrap each item in an array:
let a = [2, 4, 0, 8, 9, 15]
const result = a.map((n) => [n])
console.log(JSON.stringify(result))
let a = [2, 4, 0, 8, 9, 15];
let b = a.map((item) => [item]);
a = [2, 4, 0, 8, 9, 15]
console.log(result = a.map((n) => [n]))
b=[]
//you can try below also
for (i in a){
b.push([i]);
}

Categories