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

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>

Related

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

Find if arrays repeat and then select them [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have multiple arrays in a main/parent array like this:
var arr = [
[1, 17],
[1, 17],
[1, 17],
[2, 12],
[5, 9],
[2, 12],
[6, 2],
[2, 12],
[2, 12]
];
I have the code to select the arrays that are repeated 3 or more times (> 3) and assign it to a variable.
The code is:
var arr = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]]
arr.sort((a, b) => a[0] - b[0] || a[1] - b[1])
// define equal for array
const equal = (arr1, arr2) => arr1.every((n, j) => n === arr2[j])
let GROUP_SIZE = 3
first = 0, last = 1, res = []
while(last < arr.length){
if (equal(arr[first], arr[last])) last++
else {
if (last - first >= GROUP_SIZE) res.push(arr[first])
first = last
}
}
if (last - first >= GROUP_SIZE) res.push(arr[first])
console.log(res)
So the final result is:
console.log(repeatedArrays);
>>> [[1, 17], [2, 12]]
My problem: But the problem is, I have an array like this {from: [12, 0], to: [14, 30]}.
var arr = [
[1, 17],
[1, 17],
[1, 17],
[2, 12],
[5, 9],
[2, 12],
[6, 2],
{from: [12, 0], to: [14, 5]},
{from: [12, 0], to: [14, 5]},
{from: [4, 30], to: [8, 20]},
{from: [12, 0], to: [14, 5]},
{from: [4, 30], to: [8, 20]},
[2, 12],
[2, 12]
];
When I try to use the above code, it doesn't work. The error message is:
Uncaught TypeError: arr1.every is not a function
The final result should be:
console.log(repeatedArrays);
>>> [[1, 17], [2, 12], {from: [12, 0], to: [14, 5]}]
How can I make that code above work?
If you introduce a non array into the mix, you need to handle it differently.
Yours already work with array so I'm adding object style check for both sort and equal.
var arr = [
[1, 17],
[1, 17],
[1, 17],
[2, 12],
[5, 9],
[2, 12],
[6, 2],
{ from: [4, 30], to: [8, 21] },
{ from: [12, 0], to: [14, 5] },
{ from: [12, 0], to: [14, 5] },
{ from: [4, 30], to: [8, 20] },
{ from: [12, 0], to: [14, 5] },
{ from: [4, 30], to: [8, 20] },
[2, 12],
[2, 12]
];
arr.sort((a, b) => {
if (a instanceof Array && b instanceof Array) {
return a[0] - b[0] || a[1] - b[1]
} else if (a instanceof Array || b instanceof Array) {
return a instanceof Array ? -1 : 1
} else {
return a.from[0] - b.from[0] || a.from[1] - b.from[1] || a.to[0] - b.to[0] || a.to[1] - b.to[1]
}
});
// define equal for array
const equal = (arr1, arr2) => {
if (arr1 instanceof Array) {
return arr1.every((n, j) => n === arr2[j]);
} else {
if (arr2 instanceof Array) return false;
for (let k in arr1) {
if (!arr1[k].every((n, j) => n === arr2[k][j])) {
return false
}
}
return true;
}
};
let GROUP_SIZE = 3;
(first = 0), (last = 1), (res = []);
while (last < arr.length) {
if (equal(arr[first], arr[last])) last++;
else {
if (last - first >= GROUP_SIZE) res.push(arr[first]);
first = last;
}
}
if (last - first >= GROUP_SIZE) res.push(arr[first]);
console.log(res);
You can use the function reduce for grouping and counting the objects and then execute the function filter for getting the object with count >= 3.
var array = [ [1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12], [2, 12] ];
let result = Object.values(array.reduce((a, [c, b]) => {
let key = `${c}|${b}`;
(a[key] || (a[key] = {count: 0, value: [c, b]})).count++;
return a;
}, {})).filter(o => {
if (o.count >= 3) {
delete o.count;
return true;
}
return false;
}).map(({value}) => value);
console.log(result);
.as-console-wrapper { min-height: 100%; }
Really simple - filter it all, then remove duplicates with Set and JSON methods (because it's nested arrays not objects):
var array = [
[1, 17],
[1, 17],
[1, 17],
[2, 12],
[5, 9],
[2, 12],
[6, 2],
[2, 12],
[2, 12]
];
var repeatedArrays = [...new Set(array.filter(e => array.filter(f => JSON.stringify(e.sort()) == JSON.stringify(f.sort()))).map(JSON.stringify))].map(JSON.parse);
console.log(repeatedArrays);

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

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

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