Related
I am trying to improve in my Problem Solving Skills and would love to get some explanation on what it is that I am doing wrong or if I can get a hand in the right direction. My code below is what I am stuck on.
My problem, I am trying to check within the array if it contains any numbers that will sum up to a total given value. Pretty simple but a bit complex for a beginner.
My first Step is to setup a function with two parameters that accept the array and total amount we want.
const array = [10, 15, 7, 3];
function sumUpTotal(array, total) {
}
Then I want to iterate through my array to check each value within the array by using the forEach method to output each value
const array = [10, 15, 7, 3];
function sumUpTotal(array, total) {
array.forEach(value => value)
}
Now that I have all the outputs, I am stuck on how I can check if the numbers add up with each other to give out the total we want. Can someone please help.
The Output should be two numbers that add up to the total.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Using forEach() to iterate over each value in the array and includes() to check if any values further ahead in the array sum to your total you can generate an array of unique sum pairs. By only looking forward from the given iteration one avoids generating duplicate pairings. (eg. avoids [[10, 7], [7, 10]] for you example input)
forEach() provides both the value and the index of the current iteration, which makes it simple to use the optional, second fromIndex argument of includes() to only look ahead in the array by passing index+1. If a match is found an array of [value, difference] is pushed to the result array. The return value is an array of sum pairs, or an empty array if there are no matches.
const array = [10, -2, 15, 7, 3, 2, 19];
function sumUpTotal(array, total) {
let result = []
array.forEach((value, index) => {
let diff = total - value;
if (array.includes(diff, index + 1)) result.push([value, diff]);
});
return result;
}
console.log(JSON.stringify(sumUpTotal(array, 17)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this using a Set as follows:
function sumUpTotal(array, total) {
// initialize set
const set = new Set();
// iterate over array
for(let i = 0; i < array.length; i++){
// get element at current index
const num = array[i];
// get the remaining number from total
const remaining = total - num;
// if the remaining is already stored in the set, return numbers
if(set.has(remaining)) return [num, remaining];
// else add number to set
else set.add(num);
}
// return null if no two numbers in array that sum up to total
return null;
}
const array = [10, 15, 7, 3];
const total = 17;
console.log( sumUpTotal(array, total) );
Given an array of integers, where the values should be sorted in the following order:
if we have an array
[1, -1, -3, 9, -2, -5, 4, 8,]
we must rearrange it this way: largest number, smallest number, 2nd largest number, 2nd smallest number, ...
[9, -5, 8, -3, 4, -2, 1, -1 ]
I get the first largest and smallest numbers, but can't figure out how to make it dynamic for all values in the array.
I know that I must take two variables, say firstSmallest and firstLargest and point them to the first and last index of the array respectively, run a loop, which I do already in the code below, and store value into new array by incrementing firstSmallest and decrementing firstLargest, but couldn't implement into code.
let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => a-b);
let firstSmallest = sorted[0];
let firstLargest = sorted[unsorted.length-1];
for(let i = 0; i <= sorted.length; i++){
//I should increment firstSmallest and decrement firstLargest numbers and store in output
}
return output;
}
meanderArray(unsortedArr);
console.log(output);
You could take a toggle object which takes the property of either the first item or last from an array and iterate until no more items are available.
function meanderArray([...array]) {
const
result = [],
toggle = { shift: 'pop', pop: 'shift' };
let fn = 'shift';
array.sort((a, b) => a - b);
while (array.length) result.push(array[fn = toggle[fn]]());
return result;
}
console.log(...meanderArray([1, 5, 8, 7, 6, -1, -5, 4, 9, 5]));
You can sort an array by descending, then logic is the following: take first from start and first from end, then second from start-second from end, etc.
let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => b-a);
let output = []
for(let i = 0; i < sorted.length/2; i++){
output.push(sorted[i])
if(i !== sorted.length - 1 - i){
output.push(sorted[sorted.length - 1 - i])
}
}
return output;
}
let result = meanderArray(unsortedArr);
console.log(result);
You can sort, then loop and extract the last number with pop() and extract the first number with shift().
let unsortedArr = [1, -1, -3, 9, -2, -5, 4, 8,]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => a - b);
for(let i = 0; i < unsortedArr.length + 2; i++){
output.push(sorted.pop());
output.push(sorted.shift());
}
console.log(output);
return output;
}
meanderArray(unsortedArr);
Fastest Meandering Array method among all solutions mentioned above.
According to the JSBench.me, this solution is the fastest and for your reference i have attached a screenshot below.
I got a different approach, but i found that was very close to one of above answers from elvira.genkel.
In my solution for Meandering Array, First I sorted the given array and then i tried to find the middle of the array. After that i divided sorted array in to two arrays, which are indices from 0 to middle index and other one is from middle index to full length of sorted array.
We need to make sure that first half of array's length is greater than the second array. Other wise when applying for() loop as next step newly created array will contains some undefined values. For avoiding this issue i have incremented first array length by one.
So, always it should be firstArr.length > secondArr.length.
And planned to create new array with values in meandering order. As next step I created for() loop and try to push values from beginning of the first array and from end of the second array. Make sure that dynamically created index of second array will receive only zero or positive index. Other wise you can find undefined values inside newly created Meandering Array.
Hope this solution will be helpful for everyone, who loves to do high performance coding :)
Your comments and suggestions are welcome.
const unsorted = [1, 5, 8, 7, 6, -1, -5, 4, 9, 5];
const sorted = unsorted.sort((a,b)=>a-b).reverse();
const half = Math.round(Math.floor(sorted.length/2)) + 1;
const leftArr = sorted.slice(0, half);
const rightArr = sorted.slice(half, sorted.length);
const newArr = [];
for(let i=0; i<leftArr.length; i++) {
newArr.push(leftArr[i]);
if (rightArr.length-1-i >= 0) {
newArr.push(rightArr[rightArr.length-1-i]);
}
}
I need a hand to sum the value of array elements with the previous element(s) and return a new array.
So if we have :
let durations = [4, 3.5, 6];
then in the new array the first element is 4, the second element would be the sum of 4 + 3.5 and the third one would be 4 + 3.5 + 6; so the desired result would be [4, 7.5, 13.5]
So far it seems that reduce unexpectedly just concat the numbers and returns an array of strings !!!
let durations = [4, 3.5, 6];
let arr = [];
let durationsNew = durations.reduce((a, b) => {
arr.push(a + b);
return arr;
}, []);
console.log(durationsNew); // The desired result is [4, 7.5, 13.5]
In your code, you take the accumulator a and add the value to it. The accumulator is an array and this is converted to string by using it with a plus operator.
Instead, you could take a variable for sum and map the sum by adding the value for each element.
let durations = [4, 3.5, 6],
sum = 0,
array = durations.map(value => sum += value)
console.log(array); // [4, 7.5, 13.5]
Try this - a mixture of map() and reduce():
[4, 3.5, 6].map((num, i, arr) =>
num + arr.slice(0, i).reduce((a, b) =>
a + b, 0)); //[4, 7.5, 13.5]
The idea is to map the array to a new array, and for each number, the new number returned is the number + the sum of the array values up to that number.
If you are going to use reduce, you have to do something like this:
let durations = [4, 3.5, 6]
let durationsNew = durations.reduce((_durationsNew, duration, durationIndex) => {
if(durationIndex > 0) {
_durationsNew.push(_durationsNew[durationIndex - 1] + duration)
} else {
_durationsNew.push(duration)
}
return _durationsNew;
}, [])
console.log(durationsNew); // The desired result is [4, 7.5, 13.5]
Example: https://repl.it/repls/HandsomeVacantRate
Benchmark test with Array.map, Array.reduce, and for loop:
I have an array of values. I want to make a second array based on the first one with stricter criteria. For example, what I want specifically is:
arrayOne[1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
How would I make it so in my new array, only the values that show up 5 times are a part of the array and only show up once. Example: arrayTwo [1,4]
I'm fairly new to JavaScript and have been given an opportunity to code a decision making system for one of my business courses instead of doing the final exam. Any help you can give would be much appreciated. Thank You.
You could use a hash table, which counts each found element and then use the count for filtering and get only the fifth element as result set in a single loop.
var array = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5],
count = Object.create(null),
result = array.filter(v => (count[v] = (count[v] || 0) + 1) === 5);
console.log(result);
I commented the code with the steps I took:
const arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
function method(arr, minimum) {
//Create an object containing the amount each number occurs
const occurrences = arr.reduce((o, n) => {
//If number is already in the object add 1
if (o[n]) o[n] = o[n] + 1;
//Else set its occurence to 1
else o[n] = 1;
//Return the object for the next iteration
return o;
}, {});
//Deduplicate the array be creating a Set(every elements can only occur once) and spread it back into an array
const deduplicate = [...new Set(arr)];
//Filter array to only contain elements which have the minimum of occurences
const filtered = deduplicate.filter(n => occurrences[n] >= minimum);
return filtered;
}
console.log(method(arrayOne, 5));
You can use a Map for this.
let arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
let counterMap = new Map();
arrayOne.forEach(value => {
let valueStr = value.toString();
counterMap.set(valueStr, counterMap.has(valueStr) ? counterMap.get(valueStr) + 1 : 1);
});
let arrayTwo = [];
counterMap.forEach((value, key, map) => {
if(value >= 5) {
arrayTwo.push(key);
}
});
console.log(arrayTwo);
Not the most elegant answer, but I assume you're looking just to find all values that appear at least 5 times.
const arrayOne = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
const arrayTwo = Object.entries(arrayOne.reduce((obj, num) => {
if(!obj[num]){
obj[num] = 1
} else {
obj[num] = obj[num] + 1
}
return obj
}, {})).filter(([key, value]) => {
return value >= 5
}).map((item) => {
return parseInt(item[0])
})
console.log(arrayTwo)
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5];
Define a function that will take an array and numOfOccurrences
const filterByOcur = (arr, numOfOccurrences) => {
// create an object to act as a counter this will let us
// iterate over the array only once
const counter = {};
const res = new Set();
for (let num of arr) {
// if it's the first time we see the num set counter.num to 1;
if (!counter[num]) counter[num] = 1;
// if counter.num is greater or equal to numOfOccurrences
// and we don't have the num in the set add it to the set
else if (++counter[num] >= numOfOccurrences && !res.has(num)) res.add(num);
}
// spread the Set into an array
return [...res];
};
console.log(
filterByOcur(a, 5)
);
There is number of ways of doing this, I will try to explain this step by step:
Array declaration
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
Method to count elements in an array, we are using reducer function that as a first argument takes object where key is our value from array and has a incremental number as a value. Remeber to start reducer with empty object
const counted = a.reduce((counter, value) => {
if (counter[value]) counter[value]++
else counter[value] = 1
return counter
}, {})
Make your array unique with Set constructor
const uniq = Array.from(new Set(a))
Fire filter functions on the uniq array with a help of counted array, look how we access it:
const onlyOne = uniq.filter(val => counted[val] === 1)
const onlyFive = uniq.filter(val => counted[val] === 5)
Merge all filtered arrays into one
const final = [].concat(onlyOne, onlyFive)
I'm using a JSON array that has 38 fields and I have to sum each of the fields.
I've tried a small sample set to test how and I'm running into a problem:
I have variables called field1, field2, .... So I figured out how to create them but it looks like it sees the variables as text not the values inside them.
test1 = [[36,1500,2,3,4],[36,15,2,7,8],[36,3000,4,5,6],[36,8,7,6,15]]
for (var i = 0; i < test1.length; i++) { //get each array
for (var n = 0; n < 5; n++) { //get each item in the array
var theField = "field" + n;
theField = theField +test1[i][n]; //This fails
field2 = field2 + test1[i][2]; //This works
If I use field + n to create the variable, the sum value at the end is 0,
if I call field2 = field2 + test1[i][2] at the end of the loop I have the sum for the third value in each array. However I have to hard code field1 -> field38.
Sum by Array
let data = [
[36, 1500, 2, 3, 4],
[36, 15, 2, 7, 8],
[99, 99, 99, 99 ,99], // fake data
[36, 3000, 4, 5, 6],
[36, 8, 7, 6, 15]
]
// only pull records with 36 as value of first element
let filtered = data.filter(arr=>arr[0]==36)
// iterate over each array and sum elements at index 1...end
let sum = filtered.map(([_,...arr]) => arr.reduce((sum, val) => sum += +val, 0))
console.log(sum)
Filter the data for what you want based on the first element (stored in filtered)
Iterate over the remaining array using map(), which will return an array
Inside the map() loop, iterate over each value using reduce() to sum each element of the array
The first element is ignored using destructuring assignment/rest. The [_,...arr] means the first element will be stored in a variable called _, the rest of the elements will be stored in an array called arr, which is elements 2..5 (index:1..4).
Sum by Index
let data = [
[36, 1500, 2, 3, 4],
[36, 15, 2, 7, 8],
[99, 99, 99, 99, 99], // fake data
[36, 3000, 4, 5, 6],
[36, 8, 7, 6, 15]
]
// only pull records with 36 as value of first element
let filtered = data.filter(arr => arr[0] == 36)
// initialize array to hold sums
let sums = Array(filtered[0].length).fill(0)
// iterate over each array and each index to sum value at the index
filtered.forEach(([_, ...arr]) =>
arr.forEach((val, ndx) =>
sums[ndx] += +val
)
)
console.log(sums)
Filter the data for what you want based on the first element (stored in filtered)
Initialize the holding array of sums by index to 0
Iterate over the filtered array (rows) using forEach
Inside the forEach() loop, iterate over each value using another forEach() using the index and value to store to the sums array created earlier
The first element is ignored using destructuring assignment/rest. The [_,...arr] means the first element will be stored in a variable called _, the rest of the elements will be stored in an array called arr, which is elements 2..n (index:1..n-1).
What are you trying to do? If you are trying to sum the arrays.
const test1 = [[36,1500,2,3,4],[36,15,2,7,8],[36,3000,4,5,6],[36,8,7,6,15]];
const sum = arr => arr.reduce((total, item) => total + item, 0);
console.log(test1.reduce((total, arr) => sum(arr) + total, 0));
You can simply use map to map the array to a new array of sums using reduce to create a sum of the child arrays. This will give an array of sums, if you would like a sum of those, you can then use reduce again on that result and get a final number.
// Our starting data
let test1 = [[36,1500,2,3,4],[36,15,2,7,8],[36,3000,4,5,6],[36,8,7,6,15]]
// a simple reusable sum function
const sum = (sum, val) => sum + val
// Sum each array
let result = test1.map(arr => arr.reduce(sum, 0))
// Display the results (stringified for readability)
console.log('Each array sumed:', JSON.stringify(result))
// Sum the results if needed
console.log('Sum of all arrays:', result.reduce(sum, 0))