Divide array into two arrays and set values to odd and even - javascript

I can't get a result I wanted:
Even Array is: 2, 18, 38, -10, 0, 104
Odd Array is: 3, 13, -5, 11
Two arrays where one contains even numbers another odd.
Here is the code:
let arrayMain = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104];
let oddArray = [];
let evenArray = [];
for (let i = 0; i < arrayMain.length; i++){
if (i % 2 == 0) {
evenArray.push(arrayMain[i]);
}
else {
oddArray.push(arrayMain[i]);
}
}
console.log("Odd Array is " + oddArray);
console.log("Even Array is " + evenArray);
It gives me:
Odd Array is 3,18,38,11,104
Even Array is 2,13,-5,-10,0
How can I fix this?

You need to check the value, not the index.
if (arrayMain[i] % 2 == 0) {
// ^^^^^^^^^^ ^

Related

How can I sum array index values?

I am new to Javascript and at the moment I'm learning how "arrays" are used.
In my code below I have 12 numbers held by an array variable. Next, the for loop is iterating over the indexes to check which values have 2 or more digits, the while-loop then summarizes the digits (e.g. value '130' at index 8, will be 1+3+0=4).
Final step..and also where I'm stuck:
I need to sum up all the "new" index values and return the result in a variable.
With the numbers provided in the code, the result would be '50'.
Anyone have clue on how to do this? I've tried the conventional for-loop with sum += array[i], but it doesn't work.
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
for (var i = 0; i < arrChars.length; i++) {
var digsum = 0;
while (arrChars[i] > 0) {
digsum += arrChars[i] % 10;
arrChars[i] = Math.floor(arrChars[i] / 10);
}
var sum = 0; // this last part won't work and I just get "nan", 12 times
for (var j = 0; j < arrChars.length; j++) {
sum += parseInt(digsum[j]);
}
console.log(sum); // desired output should be '50'
}
Move digsum outside and it will contain the sum of every number in it:
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
var digsum = 0;
for (var i = 0; i < arrChars.length; i++) {
while (arrChars[i] > 0) {
digsum += arrChars[i] % 10;
arrChars[i] = Math.floor(arrChars[i] / 10);
}
}
console.log(digsum); // desired output should be '50'
I'd make this easy and just flatten the array of numbers into a string of digits, split that into an array of single digits, and add them together:
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
console.log([...arrChars.join('')].reduce((agg, cur) => agg += +cur, 0));

JS Array Interview Question - Split Array

I was given this problem at one of my interviews and was told I have 20 minutes to solve it. This is the answer I came up with ( 2 versions ). Can you let me know which version you prefer and why, and if you have a better idea of how to solve it (less complex, less memory usage, etc.) Please share.
Problem: You have an array of random numbers that range from 0 to 100 elements.
Write a function that will split this array into several arrays, each containing elements in the following range: (0-10],(10-20],(20-30], etc up to a 100].
Write a function that outputs these arrays in a form of a simple graph, where each delimiter represents a single value in the array.
Array = [10, 12, 71, 52, 51, 1, 5, 22, 21, 6, 95, 11, 3, 64, 45, 55,
65, 42, 99, 4];
Desired outcome:
5 Elements in array: ***** - 1,5,6,3,4
3 Elements in array: *** - 10,12,11
2 Elements in array: ** - 22,21
No Elements in array.
2 Elements in array: ** - 45,42
3 Elements in array: *** - 52,51,55
2 Elements in array: ** - 64,65
1 Elements in array: * - 71
No Elements in array.
2 Elements in array: ** - 95,99
// Version 1
arr = [10, 12, 71, 52, 51, 1, 5, 22, 21, 6, 95, 11, 3, 64, 45, 55, 65, 42, 99, 4];
const splitArray = (inputArray, range) => {
const newArray = [];
do {
let tempArray = [];
tempArray = inputArray.filter((item) => {
if (item >= range && item < range + 10) return item;
});
range += 10;
newArray.push(tempArray);
} while (range + 10 <= 100);
return newArray;
};
const printArrays = (array, delimiter) => {
let toPrint = "";
for (index in array) {
let stars = array[index].length;
let string = "";
for (let i = stars; i > 0; i--) {
string += delimiter;
}
toPrint += stars
? `${stars} Elements in array: ${string} - ${array[index]} \n`
: "No Elements in array. \n";
}
return toPrint;
};
console.log(printArrays(splitArray(arr, 0), "*"));
// Version 2
arr = [10, 12, 71, 52, 51, 1, 5, 22, 21, 6, 95, 11, 3, 64, 45, 55, 65, 42, 99, 4];
const getArrays = (inputArray) => {
const newArray = [];
let min = 0;
let max = 10;
do {
const tempArray = [];
for (i in arr) {
let val = arr[i];
val >= min && val < max ? tempArray.push(val) : "";
}
min += 10;
max += 10;
newArray.push(tempArray);
} while (max <= 100);
return newArray;
};
const printArrays = (array, delimiter) => {
for (index in array) {
let stars = array[index].length;
let string = "";
for (let i = stars; i > 0; i--) {
string += delimiter;
}
console.log(
stars ? `${stars} Elements in array: ${string} - ${array[index]}` : "No Elements in array."
);
}
};
printArrays(getArrays(arr), "^");
Both approaches have moderate issues.
The first approach does
let tempArray = [];
tempArray = inputArray.filter((item) => {
if (item >= range && item < range + 10) return item;
});
Better to just declare the tempArray as the filtered array to begin with.
const tempArray = inputArray.filter(...
Also, return item is suspicious inside a filter - all the filter callback cares about is whether its return value is truthy or falsey. Returning the array item when you actually want to indicate that the value should be included in the output is a common mistake. It happens not to be a problem here because 0 isn't a possibility, but it's still confusing. A better choice would be to do
const tempArray = inputArray.filter(
item => item >= range && item < range + 10
);
(and maybe rename range to startOfRange)
Both of your approaches are also iterating through the entire input array multiple times (once for each range), which seems a bit wasteful - better to iterate through the input once.
Your second approach uses for (i in arr), and both approaches are doing for (index in array). This is a bad idea, and since you don't actually care about the index you're iterating over, it'd make sense to use for..of loops instead.
I think a better looking approach that iterates through the input just once would be:
const arr = [10, 12, 71, 52, 51, 1, 5, 22, 21, 6, 95, 11, 3, 64, 45, 55, 65, 42, 99, 4];
const getArrays = (inputArray) => {
const grouped = {};
for (let i = 0; i < 100; i += 10) {
grouped[i] = [];
}
for (const item of inputArray) {
const rangeProp = Math.floor(item / 10) * 10;
grouped[rangeProp].push(item);
}
return Object.values(grouped);
};
const printArrays = (groupedArrays, delimiter) => {
for (const array of groupedArrays) {
const stars = delimiter.repeat(array.length);
console.log(
stars
? `${array.length} Elements in array: ${stars} - ${array.join(',')}`
: "No Elements in array."
);
}
};
printArrays(getArrays(arr), "*");
I will do that this way :
This approach is simple: it retrieves the values one by one and adds them to the array corresponding to their range.
const arr = [10, 12, 71, 52, 51, 1, 5, 22, 21, 6, 95, 11, 3, 64, 45, 55, 65, 42, 99, 4];
let ranges = arr.reduce((a,x)=>
{
let range = (x/10)|0 // get range start value 0 to 9
a[range] ??= [] // create the array of if it does not already exist
a[range].push(x)
return a
},{})
console.log('ranges=', ranges ) // so that noobs can visualize this result
for (let r = 0; r < 10; r++ )
{
if (!ranges[r])
document.write('No Elements in array.<br>')
else
{
let count = ranges[r].length
document.write(`${count} Elements in array: ${'*'.repeat(count)} - ${ranges[r].join(',')}<br>`)
}
}
.as-console-wrapper {max-height: 100% !important; width:20%; top: 0;
margin-left: 80%; }
.as-console-row::after {display: none !important;}
range = (x/10)|0 // get range start value 0 to 9
example in case of x = 25 -> 25/10 give 2.5 and 2.5 | 0 give 2 -> integer part value of 2.5
| is the OR boolean operator, work only on integers values so it return an interger
??= is Logical nullish assignment

Find the sum pair of the elements inside the array?

Have the function ArrayChallenge(arr) take the array of integers stored in arr, and determine if any two numbers (excluding the first element) in the array can sum up to the first element in the array. For example: if arr is [7, 3, 5, 2, -4, 8, 11], then there are actually two pairs that sum to the number 7: [5, 2] and [-4, 11]. Your program should return all pairs, with the numbers separated by a comma, in the order the first number appears in the array. Pairs should be separated by a space. So for the example above, your program would return: 5,2 -4,11
If there are no two numbers that sum to the first element in the array, return -1
Input: [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]
Output: 6,11 10,7 15,2
Final Output: --6--,--1----1-- --1--0,7 --1----5--,2
Input: [7, 6, 4, 1, 7, -2, 3, 12]
Output: 6,1 4,3
Final Output: --6--,--1-- 4,3
My approach
function ArrayChallenge(arr) {
var sum = []
for (var i = 0; i < arr.length; i++){
for (var j = i + 1; j < arr.length; j++){
if(arr.[i] + arr[j]=== )
}
}
// code goes here
return arr;
}
// keep this function call here
console.log(ArrayChallenge(readline()));
Can you please help me with this ?
Logic
Loop through the array.
Start from index 1 to last node (except index 0) in the outer loop.
Srart from one node next to the outer loop in the inner loop.
Check the sum of both nodes.
If the sum value is same as the node at first index, push that to sum array in required format.
Check the length of sum array. If length > 0 the join sum array and return. Else return -1
Working Code
const input = [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7];
const input2 = [7, 6, 4, 1, 7, -2, 3, 12];
const input3 = [37, 6, 4, 1, 7, -2, 3, 12];
function ArrayChallenge(arr) {
var sum = []
for (var i = 1; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === arr[0]) {
sum.push([arr[i], arr[j]].join());
}
}
}
return sum.length > 0 ? sum.join(" ") : -1;
}
console.log(ArrayChallenge(input));
console.log(ArrayChallenge(input2));
console.log(ArrayChallenge(input3));
Your approach uses a O(n^2) level complexity. This can be solved using O(n) if you're willing so sacrifice a little on space complexity.
What you can do is :
Make an empty object.
store all values of the array (not the 0th element) in the object as key and add it's value as true.
Loop the array (from 1st index). Take the value and subtract it from the 0th element. find this subtracted value from the object, If it does not return undefined, make a pair and save it.
One drawback of this method is, you'll find duplicate entries in the result.
This Approach uses O(n) Time complexity and O(n) space complexity
function ArrayChallange(arr) {
let numObj = {}
let i = 1
let result = []
let tempVal
// Pushing all elements of arr (from index 1) inside numObj
while(i<arr.length){
numObj[arr[i]] = true
}
i = 1
// Looping the array to find pairs
while(i < arr.length){
tempVal = numObj[Math.abs(arr[0] - arr[i])]
if(tempVal){
result.push(arr[i].toString() +","+tempVal.toString())
}
}
if(result.length !== 0)
return result.join(" ")
else
return -1
}
You could use a reducer followed by a forEach loop in order to push the pairs to an empty array, then join them at the end.
const ArrayChallenge = (nums) => {
const pairs = []
// Get the first and remove it from the array
const first = nums.splice(0, 1)[0]
nums.reduce((all, curr) => {
all.forEach((a) => {
// Check if we have a match
if (curr + a === first) {
// check if it's already in the array
// we don't want duplicates
if (pairs.indexOf(`${a},${curr}`) === -1 && pairs.indexOf(`${curr},${a}`) === -1) {
// push the pair to the array separated by a space
pairs.push(`${curr},${a}`)
}
}
})
return all
}, nums) // we pass in nums as the starting point
// If there are no pairs then return -1
if (pairs.length === 0) {
return -1
} else {
// Join the pairs together with a space
const result = pairs.join(' ')
// Replace each digit (\d) with hyphens before and after
const parsed = result.replace(/(\d)/g, '--$1--')
return parsed
}
}
const result1 = ArrayChallenge([17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7])
console.log(result1)
const result2 = ArrayChallenge([7, 6, 4, 1, 7, -2, 3, 12])
console.log(result2)

Why is splicing an array in JavaScript removing the last few elements?

I'm currently working on an array function that converts subarrays of consecutive numbers into strings denoting that range of numbers — for example, this array...
[1, 2, 3, 6, 8, 10, 11, 12, 15, 18]
...would become this array:
["1-3", 6, 8, "10-12", 15, 18]
I've been able to develop a function that mostly works, but I've encountered a weird error where all the elements past the final range of numbers spliced into the array are completely deleted. For example, the test array above actually becomes this:
["1-3", 6, 8, "10-12"]
This is the code I've written so far. It's not super pretty yet, but as I mentioned above, it gets the job done right up until the very end:
let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];
for (i = 0; i < testArray.length; i++) {
let consecutives = [];
consecutives.push(testArray[i]);
let j = i + 1;
while (j < testArray.length) {
if (testArray[j] == (testArray[j - 1] + 1)) {
consecutives.push(testArray[j]);
j++;
} else {
break;
}
}
if (consecutives.length > 2) {
let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
console.log(testArray);
console.log(testArray[i]);
console.log(testArray[j]);
testArray.splice(i, j, range);
}
}
console.log(testArray);
These are the console logs output by that code:
Array(10) [ 1, 2, 3, 6, 8, 10, 11, 12, 15, 18 ]
1
6
Array(8) [ "1-3", 6, 8, 10, 11, 12, 15, 18 ]
10
15
Array(4) [ "1-3", 6, 8, "10-12" ]
I initially figured this was caused by a mix-up with array indexes, but playing around with the index-1s hasn't fixed the problem yet. Has anyone else ever had a similar issue with JavaScript's splicing, and if so, how were you able to get it working?
The problem lies in one line of code:
testArray.splice(i, j, range);
According to the MDN, the second argument specifies how many elements in the array to delete.
deleteCount
An integer indicating the number of elements in the array to remove from start.
However, the code defines this argument as the index of the last array to remove from:
let j = i + 1;
The solution is to get the difference between i and j before passing it to splice:
testArray.splice(i, j - i, range);
When you do:
testArray.splice(i, j, range);
You are forgetting that j is the right limit index of the array that you want to erase, so you need to subtract i that is the left limit:
testArray.splice(i, j - i, range);
let testArray = [1, 2, 3, 6, 8, 10, 11, 12, 15, 18];
for (i = 0; i < testArray.length; i++) {
let consecutives = [];
consecutives.push(testArray[i]);
let j = i + 1;
while (j < testArray.length) {
if (testArray[j] == (testArray[j - 1] + 1)) {
consecutives.push(testArray[j]);
j++;
} else {
break;
}
}
if (consecutives.length > 2) { // doesn´t it should be > 1 ??
let range = String(testArray[i]) + "-" + String(testArray[j - 1]);
console.log(testArray);
console.log(testArray[i]);
console.log(testArray[j]);
testArray.splice(i, j - i, range);
}
}
console.log(testArray);

Find all unique values that are sums of sub-arrays of an array of numbers... simple?

Sup fellow geeks!
I'm trying to make an array that lists all the possible values of the sums of the elements of an array. I'm sure this must be quite easy but I'm up to 2 or 3 hours now and I'm getting frustrated, I think I'm almost there...
var frootVals = [0,1,2,3,4,5]
var frootInc = frootVals
var fruitEnd = frootInc[frootInc.length-1]//begins at 5
var fruitAll = 15 // The total of all the numbers in the array. (this is actually
// calculated in another function, but lets just say I declared it as 15)
for (e = frootVals.length-2 ;fruitEnd !== fruitAll;e--){ //so I want it to
//finish when the final array entry is 15.
for (p = 1;p < e; p++){
var incEnd = frootInc[frootInc.length-p]
frootInc.push(incEnd + frootVals[p]) //1st time round (5 + 1 = 6, 5 + 2 = 7,
//5 + 3 =8, 5 + 4 = 9) THEN start again with 9 now being incEnd so pushes
//9+1 = 10 etc etc until the last digit is 15 and the whole loop stops...
}
}
EDIT - Basically the final result I'm after is frootInc to be be an array of the integers [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] - I'm sure I'll kick myself for giving up but I've only been learning a few weeks so this is all quite brain taxing.
After thinking about your question a bit, I think the easiest solution would be with recursion when the condition that the final value added to the array is less than the sum of values.
Here's a JS Fiddle for demo: http://jsfiddle.net/ukgzwpky/
To break it down a bit (and so that you may confirm I have the question right :D), say we have the following array:
[0, 1, 2, 3, 10, 15, 30]
The sum of the values are: 61. So the expected output array would be:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
To further break it down, the looping logic would do something like this:
// Get final value to add to previous values
var val = [0, 1, 2, 3, 10, 15, 30].pop();
// Add the final value - 30 - to all previous values (ignoring the zero)
.. loop here and push the values to our array ...
// For the first iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45]
// New values calculated from: 30 + 1, 30 + 2, 30 + 3, 30 + 10, 30 + 15
At this point, our max value of 61 is less than the final value of 45 So, we do it again!
var val = [0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45].pop();
.. loop here and push the values to our array ...
// Second iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
// New values are: 45 + 1, 45 + 2, 45 + 3, 45 + 10, 45 + 15
// Note that 45 + 30 would be greater than our sum of 61, so we break
If that's correct, here's a script that I wrote that populates such an array:
function getPopulatedArray(arr) {
var max = arguments[1] || getSum(arr),
current = arr.pop(),
temp = [],
i = 1,
len = arr.length;
// Populate temp array with values
for (; i < len; i++) {
if ((arr[i] + current) < max) {
temp.push(arr[i] + current);
} else {
temp.push(max);
break;
}
}
arr.push(current);
arr = arr.concat(temp);
// Done? Or should we continue?
if (arr[arr.length - 1] < max) {
return getPopulatedArray(arr, max);
} else {
return arr;
}
}
Again, the JS fiddle for demonstration: http://jsfiddle.net/ukgzwpky/
Hopefully this helps!
A very simple solution would be to do something like this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){ // Iterate over the array twice
for (var j = 0; j < frootVals.length; j++){ // To calculate all combinations
result.push(frootVals[i] + frootVals[j]);
}
}
Now, if you don't want duplicates, try this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){
for (var j = 0; j < frootVals.length; j++){
var value = frootVals[i] + frootVals[j];
if(result.indexOf(value) === -1){
result.push(value);
}
}
}
You could then use result = result.sort() if you want to output a sorted result.

Categories