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]]));
}
Related
I'm trying to return the largest number in each of the sub-arrays - but this is returning the first two values of each sub-array. Seems pretty simple and yet I can't find where I go wrong.
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
newArr.push(maxVal)
}
}
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))
This code returns the following: [ 4, 5, 13, 27, 32, 35, 37, 39, 1000, 1001 ]. Where am I going wrong? I don't want to use .sort()
The problem is, you push a new value whenever a new max value is found and not deleting the previously pushed value from the current set, you need to store the maxVal until the end of the inner loop and push the value afterwards, so you only push one value for each array, which is actually the biggest one
Your function should look similar to this:
function largestOfFour (arr) {
let maxVal = 0;
let newArr = [];
for (i = 0; i < arr.length; i++) {
// reset maxVal, for new set of numbers
maxVal = 0;
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
// new largest number found
maxVal = arr[i][j];
}
}
// push highest number found in set
newArr.push(maxVal);
}
return newArr
}
I don't know whether this is allowed, but it will get you the result:
const arr=[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
console.log(arr.map(a=>Math.max(...a)))
I prefer #CarstenMassmann's answer; however, just so you can understand how your code was in error, but very close, see this edit to the original attempt.
That inner conditional doesn't find the max of the sub-array, if finds the interim max. Don't push to your results inside the condition, finish iterating the sub-array and then push the best interim max...
function largestOfFour (arr) {
let maxVal = 0
let newArr = []
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxVal) {
maxVal = arr[i][j]
// don't push here. maxVal is just the max *for now*
}
}
newArr.push(maxVal) // push here
}
return newArr
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))
I am a beginner in Javascript and I should write a code to solve this 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. and write this code can u tell me what is the problem him thnx:
function largestOfFour(arr) {
var pos = 0;
var max = 0;
var add = 0;
var sum = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (j === 4) {
sum[i] = add;
} else {
add = add + arr[i];
}
}
for (var i = 0; i < arr.length; i++) {
if (sum[i] > max) {
max = sum[i]
pos = i;
}
}
return arr[pos];
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
If you have no restrictions, you could take
Array#map for getting a new array with
Math.max for getting a maximum number and take
spread syntax ... for converting an array to parameters.
const largestOfFour = array => array.map(a => Math.max(...a));
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
For a more classic style, you could separate the functions, one for processing the outer array and one for getting a maximum value.
function max(array) {
var max = array[0];
for (let i = 1; i < array.length; i++) {
if (max < array[i]) max = array[i];
}
return max;
}
function largestOfFour(array) {
var result = [];
for (let a of array) result.push(max(a));
return result;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
I'm trying to figure out how to get the below code to push the biggestNumber variable to the largestNumbers variable so that the largest number in each sub-array of largestOfFour will be returned as an array of largestNumbers.
I see it mentally and thought that I was writing the code correctly. This is my thought process:
1) largestNumbers is set up as an empty array.
2) create a for loop that will pull each sub-array during a loop and store it as PulledSubArray.
3) I need to loop through the sub-array(pulled
SubArray) with a for loop.
4) biggestNumber variable is set-up to store the biggest number in the sub-array and an if statement is set-up to determine which number is the biggest and then push that number to the largestNumbers array.
5) break the inner for loop and then repeat steps for second sub-array.
Without giving the answer to the entire challenge, could you tell me what syntax or elements I'm missing to achieve my end result
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i > arr.length; i++){
var pulledSubArray = arr[i];
for (var n = 0; n > pulledSubArray.length; n++){
var biggestNumber = 0;
if (pulledSubArray[n] > biggestNumber){
biggestNumber = pulledSubArray[n];
} else if (pulledSubArray[n] < biggestNumber){
largestNumbers.push(biggestNumber);
break;
}
}
}
return largestNumbers;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
for (var i = 0; i > arr.length; i++){
^
Wrong condition
Your loop constructs are wrong. Correct them. A simple version of your function looks like (ECMAScript6)
const largestOfFour = (arr) => arr.map(el => Math.max(...el));
In case you want to stick to your thought
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i < arr.length; i++) { // Correct loop condition
var pulledSubArray = arr[i];
var biggestNumber = pulledSubArray[0];
for (var n = 1; n < pulledSubArray.length; n++) { // Correct loop condition
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
}
}
largestNumbers.push(biggestNumber); // Push biggest number outside the inner loop
}
return largestNumbers;
}
console.log(largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]));
Issue is with Code:
Logic:
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
} else if (pulledSubArray[n] < biggestNumber) {
largestNumbers.push(biggestNumber);
break;
}
For an array [4, 5, 1, 3], for second iteration, biggestNumber holds 4 and pulledSubArray[n] will hold 5. For this case, is you would push the value and break the loop. But you are not checking the entire array. So you will not get accurate result.
Loop condition:
for (var i = 0; i > arr.length; i++){
This will never enter the loop. It should be i < arr.length
Variable declaration:
for (var n = 0; n > pulledSubArray.length; n++) {
var biggestNumber = 0;
if (pulledSubArray[n] > biggestNumber) {
Variable should be declared outside the loop. You are currently setting its value to 0 in every iteration. So you will eventually get the last value as if (pulledSubArray[n] > biggestNumber) will always return true.
Updated Code:
function largestOfFour(arr) {
var largestNumbers = [];
for (var i = 0; i < arr.length; i++) {
var pulledSubArray = arr[i];
var biggestNumber = 0;
for (var n = 0; n < pulledSubArray.length; n++) {
if (pulledSubArray[n] > biggestNumber) {
biggestNumber = pulledSubArray[n];
}
}
largestNumbers.push(biggestNumber)
}
return largestNumbers;
}
var list = largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]);
console.log(list)
If you want to get largest number in each sub array:
var data = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
function largestOfFour(data) {
return data.map(function(d) {
return Math.max.apply(null, d)
})
}
console.log(largestOfFour(data))
Or even shorter (es6):
let data = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
const largestOfFour = data => data.map(d => Math.max.apply(null, d))
console.log(largestOfFour(data))
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]]);
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.