I have an array of arrays in javascript set up within an object that I'm storing with local storage. It's high scores for a Phonegap game in the format {'0':[[score,time],[score,time]} where 0 is the category. I'm able to see the scores using a[1][0]. I want to sort with the high scores first.
var c={'0':[[100,11],[150,12]};
c.sort(function(){
x=a[0];
y=b[0];
return y-x;
}
However, b[0] always gives an undefined error.
I'm new to Javascript and making this is my first major test as a learning experience. Though I've looked at a number of examples on stackoverflow still can't figured this one out.
You need to declare the parameters to the comparator function.
c.sort(function(){
should be
c.sort(function(a, b){
and you need to call sort on an array as "am not i am" points out so
var c={'0':[[100,11],[150,12]]};
c[0].sort(function(a, b){
var x=a[0];
var y=b[0];
return y-x;
});
leaves c in the following state:
{
"0": [
[150, 12],
[100, 11]
]
}
function largestOfFour(arr) {
for(var x = 0; x < arr.length; x++){
arr[x] = arr[x].sort(function(a,b){
return b - a;
});
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
var myArray = [ [11, 5, 6, 3, 10], [22,55,33,66,11,00], [32, 35, 37, 39], [1000, 1001, 1002, 1003, 999]];
_.eachRight(myArray, function(value) {
var descending = _.sortBy(value).reverse();
console.log(descending);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
Related
I've been trying to solve this practice problem:
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
But my code only returns the single element of from the whole array, if I unshift all the max elements it produces totally wrong results, I tried to execute the nested loop separately and it worked fine but it creates a problem when combined with outer loop.
function largestOfFour(arr)
{
// You can do this!
var max = 0;
var largestArray =[];
for (var i = 0; i <4; i++)
{
for (var j = 0; j <4; j++)
{
if (arr[i][j]>max)
{
max=arr[i][j];
largestArray.unshift(max);
//console.log(max);
}
}
}
console.log(largestArray);
return max;
}
largestOfFour([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
How to fix your code (see comments in code):
function largestOf(arr) {
var max;
var largestArray = [];
for (var i = 0; i < arr.length; i++) { // the arr length is the number of sub arrays
max = -Infinity; // max should be reinitialized to the lowest number on each loop
for (var j = 0; j < arr[i].length; j++) { // the length is the number of items in the sub array
if (arr[i][j] > max) { // just update max to a higher number
max = arr[i][j];
}
}
largestArray.push(max); // push max after the internal loop is done, and max is known
}
return largestArray; // return the largest array
}
var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);
Another solution is to use Array#map, and apply Math#max to each sub array to get it's maximum value:
function largestOf(arr) {
return arr.map(function(s) {
return Math.max.apply(Math, s);
});
}
var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);
You can do
function largestOfFour(arr)
{
return arr.map(e => Math.max(...e));
}
let result = largestOfFour([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);
Hopefully this helps:
var pre = onload, largestOfFour; // for use on other loads
onload = function(){
if(pre)pre(); // change var pre name if using technique on other pages
function largestOfFour(arrayOfFours){
for(var i=0,a=[],l=arrayOfFours.length; i<l; i++){
a.push(Math.max.apply(null, arrayOfFours[i]));
}
return a;
}
console.log(largestOfFour([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
}
I've got couple arrays I want to horizontally merge:
data1 = [["ID"], [21], [26], [32]]
data2 = [["A", "B", "C"],[10, 10, 10], [95, 95, 95], [95, 95, 95]]
Both array always have the same number of "rows"
I'm looking for this result:
result = [["ID", "A" , "B", "C"],[21, 10, 10, 10]...]
Currently I have the following code:
for ( var i = 0; i < data1.length; i++ ) {
data3.push( [ data1[i], data2[i] ] );
}
Which is giving me a strange result and I don't really understand why.
[[["A"], [10, 10 ,10]]]
Any help? I always struggle with Arrays.
That is not a weird result.
To achieve what you need, please try this
data3.push( data2[i].unshift(data1[i][0]) );
Assumption: A, B, C are Strings, like 'A'
Suggestion: You should follow a better datastructure. but still try the below solution. Array index starts from 1. You kept on changing the question, and I need to update my answer accordingly. I tried the below, it works for me.
var data1 = [["ID"], [21], [26], [32]];
var data2 = [["A", "B", "C"],[10, 10, 10], [95, 95, 95], [95, 95, 95]];
var data3 = [];
for ( var i = 0; i < data1.length; i++ ) {
data2[i].unshift(data1[i][0]);
data3.push(data2[i] );
}
console.log(data3)
Gives me the following output
[["ID","A","B","C"], [21, 10, 10, 10], [26, 95, 95, 95] ,[32, 95, 95, 95]]
I'm trying to find the maximum values of a multidimensional array.
Input:
[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
Result:
[5, 27, 39, 1001]
What I've tried:
var largestArr = [];
function largestOfFour(arr) {
for (var i = 0; i < arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j = 0; j < stop; j++) {
if (currentArr[0] > largest) {
largest = currentArr[0];
largestArr.push(largest);
largestArr.shift();
}
}
return largestArr;
}
}
largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]);
Can anyone help me understand why this isn't working?
The problem is here
if (currentArr[0]>largest){
largest = currentArr[0];
//
}
This should be done like below:
if (currentArr[j]>largest){
largest = currentArr[j];
//
}
Why this is wrong?
This is wrong because you always compare the first item of each array with the largest and not all the items in each array one after the other.
Furthermore, you have to make a few more corrections.
Specifficaly, there isn't any need to use the shift method. You have only to push the largest value of each array after the end of each processing in the largestArr. Last, but not least you have to move the return statement of the largestArr out of the for loops.
var largestArr = [];
function largestOfFour(arr) {
for (var i=0; i<arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j=0; j<stop; j++){
if (currentArr[j]>largest){
largest = currentArr[j];
}
}
largestArr.push(largest);
}
return largestArr;
}
alert(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
Since the answer has been provided here's some code can do the same job in a smaller number of lines that you might find useful in the future using reduce.
var out = arr.reduce(function (p, c) {
return p.concat(Math.max.apply(null, c));
}, []);
DEMO
Christos' answer is correct and should the selected as answer.
Additionally though, you should not pollute the global namespace by declaring largestArray outside of the function, considering that you are returning said array anyway.
function largestOfFour(arr) {
var largestArr = []; // put this line here instead of making it global
for (var i=0; i<arr.length; i++) {
var largest = 0;
var currentArr = arr[i];
var stop = currentArr.length;
for (var j=0; j<stop; j++){
if (currentArr[j]>largest){
largest = currentArr[0];
}
}
largestArr.push(largest);
}
return largestArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
This question already has answers here:
Creating an array consisting of the largest values of each sub-array does not work as expected
(4 answers)
Closed 7 years ago.
I want to extract the largest number of every single array. I believe it should be possible with the .map function.
This is what I have so far, but unfortunately this returns " [ undefined, undefined, undefined, undefined ]"
Code:
function largestOfFour(largestOfFour) {
largestOfFour.forEach(function(number){
number.sort(function(a, b){
return b - a;
});
highestValue = number.map(function(number){
return number[0];
});
});
};
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
You're iterating over the outer array,
function largestOfFour(largestOfFour) {
largestOfFour.forEach(function(number){
and then sorting the inner arrays,
number.sort(function(a, b){
return b - a;
});
and then of those inner arrays you're trying to acquire the [0] property from each value, which is undefined
highestValue = number.map(function(number){
// you redefine `number` here to be the value within the inner array
return number[0];
});
What you probably want to do is map the outer array:
function largestOfFour(largestOfFour) {
largestOfFour.map(function(numbers){
sort the inner arrays:
numbers.sort(function(a, b){
return b - a;
});
and then return the first value:
return numbers[0];
All together it probably should be:
function largestOfFour(largestOfFour) {
return largestOfFour.map(function(numbers){
numbers.sort(function(a, b){
return b - a;
});
return numbers[0];
});
}
Although there are simpler ways to find the maximum values of an array of arrays.
One such example is to use Array.prototype.reduce:
function largestValues(outer) {
return outer.map(function (inner) {
return inner.reduce(function (prev, current) {
return Math.max(prev, current);
}, Number.NEGATIVE_INFINITY);
});
}
There's a shorter way of finding the largest number in each array using Math.max:
function largestOfFour(arr) {
return arr.map(function (el) {
return Math.max.apply(null, el);
});
}; // [ 5, 27, 39, 1001 ]
DEMO
http://jsfiddle.net/y48qz6hx/
Just fixed your code
function largestOfFour(largestOfFour) {
largestOfFour.forEach(function(number, index){
number.sort(function(a, b){
return b - a;
});
largestOfFour[index] = number[0];
});
alert(largestOfFour);
};
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
try this:
var ar=[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
console.log( ar.map(x=> Math.max.apply(null, x)) )
Here is my current code:
var largestNumbers = new Array(4);
function largestOfFour(arr) {
var biggest = Math.max.apply(null, largestOfFour)
for (var index in arr) {
for(var i=0; i < arr[index].length; i++){
if (arr[index] > biggest){
arr[index].push(largestNumbers);
}
else if (arr[index] < biggest) {
arr[index].splice(0, 1);
}
}
}
return largestNumbers;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
My objective is to find the largest number in each of the subarrays and then put those values into another array and then return that value. I have been searching around for things like "How to extract a subarray from array" and that has led to me using the splice function. I'm not sure if I'm using it right, but I'm trying everything I've got because I've been stuck on this problem for 2 days now. If anyone could just lead me in the path to solve this problem, I would be more than grateful. Thank you all so much.
Furthermore, I was using this site to try and guide me along. There is a snippet of code that attempts to resolve a problem similar to mine in the latter half of the page. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
var largest = function largest(arr) {
return arr.map(function(arr) {
return Math.max.apply(null, arr);
});
};
Working example
Use map to create a new Array by looping over the first level.
Use Math.max to get the maximum value from a list of numbers
Use apply to convert the array to arguments in Math.max
function largestOfFour(arr) {
return arr.map(function(array) {
return Math.max.apply(Math, array)
});
}
var myArray = [
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
];
console.log(largestOfFour(myArray));
Applying simple nested loop's logic.
function largestOfFour(arr) {
var maxArray = [];
for(var i = 0; i < arr.length; i++) {
var maxE = 0;
for(var j = 0; j < arr.length; j++) {
if(maxE < arr[i][j]) {
maxE = arr[i][j];
}
}
maxArray.push(maxE);
}
arr = maxArray;
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
OR Try this
function largestOfFour(arr) {
var maxArray = [];
for(var i = 0; i < arr.length; i++) {
var maxE = Math.max(...arr[i]); // this spread is only available in ES6 so can be replaced by --> Math.max.apply(null, arr[i])
maxArray.push(maxE);
}
arr = maxArray;
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Just do it with a simple nested loop. Find the biggest number for each inner array and add it to the result:
function largestOfFour(arr) {
var result = [];
for(var i = 0; i < arr.length; i++){
var max = 0;
var inner = arr[i];
for(var j = 0; j < inner.length; j++){
if(inner[j] > max)
max = inner[j];
}
result.push(max);
}
return result;
}
var output = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
// [5, 27, 39, 1001]
Here is a working example
function largestOfFour(arr) {
return arr.reduce(function(p, c, index, arr){
p.push(Math.max.apply(null, c));
return p;
}, []);
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Even you can code like this also , creating a new array showing in them also
function largestOfFour(arr) {
// You can do this!
var newArray=[];
for(i=0;i<arr.length;i++){
newArray.push(Math.max.apply(Math,arr[i]));
}
return newArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
var largestNumbers = new Array();
function largestOfFour(arr) {
for (var i = 0 ; i< arr.length; i ++) {
largestNumbers.push(Math.max.apply(Math, arr[i]));
}
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Using the approach with Math.max.apply() you can do that with one loop that iterates through the array as argument;
function largestOfFour(arr){
var result = [];
for(var i = 0 ; i < arr.length ; i++){
result[i] = Math.max.apply(null, arr[i]);
}
return result;
}
EDIT:
As #Jeff Shaver posted a simpler solution, you should use the map function to return the result array.