find the smallest number in a array of an array - javascript

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

Related

Shuffle nested arrays in Javascript

I'm trying to sort multiple arrays within an array (which also has to be shuffled). A simplified example is:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
...
];
const shuffled = shuffle(toShuffle);
// outout would look something like:
// [
// [8, 6, 5, 7, 9],
// [4, 3, 1, 5, 2],
// [19, 26, 10, 67],
// ...
// ]
This needs to be flexible, so any number of arrays with any amount of values should be valid.
Here is what I've tried:
function shuffle(a) {
for (let e in a) {
if (Array.isArray(a[e])) {
a[e] = shuffle(a[e]);
} else {
a.splice(e, 1);
a.splice(Math.floor(Math.random() * a.length), 0, a[e]);
}
}
return a;
}
console.log("Shuffled: " + shuffle([
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1]
]))
But it's not working as intended. Is their an easier way to do this? Or is my code correct and just buggy.
You can use Array.from() to create a new shallow-copied array and then to shuffle Array.prototype.sort() combined with Math.random()
Code:
const toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
]
const shuffle = a => Array.from(a).sort(() => .5 - Math.random())
const result = toShuffle.map(shuffle)
console.log('Shuffled:', JSON.stringify(result))
console.log('To shuffle:', JSON.stringify(toShuffle))
You almost got it. The problem is that you are removing one item from an array, instead of capturing the removed item and them placing in a random position:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];
function shuffle(a) {
a = [...a]; //clone array
for (let e in a) {
if (Array.isArray(a[e])) {
a[e] = shuffle(a[e]);
} else {
a.splice(~~(Math.random() * a.length), 0, a.splice(e, 1)[0]);
}
}
return a;
}
console.log(JSON.stringify(shuffle(toShuffle)))
console.log(JSON.stringify(toShuffle))
[EDIT]
The original code did not shuffle the parent array, if you need shuffle everything recursively, you can use this:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];
function shuffle(a) {
a = a.map(i => Array.isArray(i) ? shuffle(i) : i); //clone array
a.sort(i => ~~(Math.random() * 2) - 1); //shuffle
return a;
}
console.log("shuffled", JSON.stringify(shuffle(toShuffle)))
console.log("original", JSON.stringify(toShuffle))

how to form array of arrays from object array in java script

Am trying form data from object array to array of arrays in JavaScript but am unable to get the result
Input Data { "sept" : [1,2,3], "oct" : [5,6,7] "Nov" : [7,8,9]}
Expected Output [["sept",1,2,3],["oct",5,6,7],["Nov",7,8,9]]
I have tried a lot I can able to get the keys by Object.Key() but can able to form the data with the value as expected output above, please help me to resolve this Thanks in advance
You could get the entries and map key and values in an array.
const
data = { sept: [1, 2, 3], oct: [5, 6, 7], Nov: [7, 8, 9] },
result = Object.entries(data).map(([k, v]) => [k, ...v]);
console.log(result);
Just iterate over properties using for .. in loop, you will get the result.
const obj = {
"sept": [1, 2, 3],
"oct": [5, 6, 7],
"Nov": [7, 8, 9],
}
const result = [];
for (const prop in obj) {
result.push([prop, ...obj[prop]]);
}
console.log(result)
Use Object.entries() and then .map() with ... - rest/spread operator
const object = {
september: [1, 2, 3],
october: [5, 6, 7],
november: [7, 8, 9],
}
const result = Object.entries(object).map(([key, value])=>[key, ...value])
You could use Object.entries then spread the values along with the key
const data = { sept: [1, 2, 3], oct: [5, 6, 7], Nov: [7, 8, 9] }
const res = Object.entries(data).map(([key, value]) => [key, ...value])
console.log(res)
The Ramda.js library has a function that does exactly this called toPairs()
https://ramdajs.com/docs/#toPairs

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

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

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