Appending new keys, and changing values in for/if loop - javascript

My current goal is to take items in array integers and create a key pair value based on how many times the key appeared in integers. My logic is: for i in integers, if i is in integers 2 already, increment that key's value by 1. if it doesn't exist, create the key and pair it with a value of 1. It's been a few hours now and after heavy googling I can't seem to find where im messing my logic up.
//require realdine-sync module
var readlineSync = require('readline-sync');
//initialize variable and list
var integer;
integers2 = {};
var integers = [];
//user input
integer = readlineSync.question('Integer?: ')
//check user input and append any integer besides 0
while (integer != 0 && integer >= 1 && integer <= 100){
console.log("not 0!")
integers.push(integer)
integer = readlineSync.question('Integer?: ')
}
console.log(integers);
for(i in integers){if (i in integers2){integers2[i] += 1}else{integers2[i] = 1}
}
console.log(integers2)

let integers2 = {}
integers = [5, 4, 5, 2, 4, 7, 5];
// you were using 'in' instead 'of', 'in': gives you index , 'of'?: gives you value of array
for (let i of integers) {
if (integers2[i]) { // if key exist increment value by one
integers2[i] += 1
} else { // else add 1 as the first value
integers2[i] = 1
}
}
console.log(integers2);

This is a solution that you can try which works. It uses the same logic as you described in the question. This solution uses Array.prototype.reduce() with a Map().
const howMany = arr => arr
.reduce(
(map, n) => map.set(n, (map.get(n) ?? 0) + 1),
new Map()
)
console.log([...howMany([3, 4, 6, 4, 5, 5, 5])])

Related

Move Zeros logic break down Javascript

I am working through this solution that I saw in this discussion section of leetcode and am unable to grasp part of the logic. The name of the game is to move all zeros to the end of a given array in place while maintaining the order of the other numbers. The increment operator inside the index of j is where I am lost because wouldn't that place the non-zero number to the right?
var moveZeroes = function(nums) {
let j = 0
for(let i = 0; i < nums.length; i++) {
if(nums[i] !== 0) {
//storing the index we are iterating on
let n = nums[i]
//changing the index in place to 0
nums[i] = 0
//console.log(nums);
//
nums[j++] = n
console.log(nums);
}
}
return nums;
};
console.log(moveZeroes([0,1,0,3,12]));
Remember that j++ is post-increment, so the initial value of j is used to index nums and then j is incremented. If it was ++j then j would be incremented first, then used.
Simply Remove All Zeros. Add Removed Zeros to the end.
var moveZeroes = (nums) =>
(
nums.toString().replaceAll("0,", "") +
",0".repeat(("" + nums).replace(/[^0]/g, "").length)
)
.split(",")
.map(Number);
console.log(moveZeroes([0, 1, 0, 0, 3, 0, 12])); //[ 1, 3, 12, 0, 0, 0, 0 ]
NOTE:
(""+nums).replace(/[^0]/g,'').length: number of 0 in the Array
nums.toString(): To convert array to string we use or we could use the trick of concatenating with an empty string like ""+nums
split(','): To convert string into an array
map(Number): To convert an array of strings to numbers.
Update
OP wants to mutate the array, "Solution A" deals with immutable arrays and "Sulution B" nutates the array.
Solution A (Immuatable)
Try using Array.filter() to separate zeroes (ex. num === 0) and numbers that are not zeroes (ex. num !== 0) into two new and separate arrays. Then use either Array.concat() or the spread operator to merge them into a single array.
// log() is an optional utility function that formats console logs
const log = data => console.log(`[${data}]`);
// This input array has zeroes everywhere
const numbers = [0, 1, 0, 0, 3, 0, 12];
const moveZeroes = array => {
// With the given array called "numbers"
// left = [1, 3, 13]
const left = array.filter(num => num !== 0);
// right = [0, 0, 0, 0]
const right = array.filter(num => num === 0);
// Then arrays "left" and "right" are merged
return [].concat(left, right)
};
log(moveZeroes(numbers));
Solution B (Muatable)
Array.reverse() the array, track the index with Array.entries(), and run it through a for...of loop. If a number isn't a zero, Array.splice() it out then Array.unshift() it to the beginning of the array. Note, .reverse(), .splice(), and .unshift() are mutating Array methods.
// log() is an optional utility function that formats console logs
const log = data => console.log(`[${data}]`);
// This input array has zeroes everywhere
const numbers = [0, 1, 0, 0, 3, 0, 12];
const moveZeroes = array => {
/* .reverse() the array, track index with
.entries(), and loop thru with a for...of
loop */
for (let [idx, num] of array.reverse().entries()) {
/* if a number isn't zero, remove it with
.splice(), then .unshift() it into the
beginning of array */
if (num !== 0) {
array.splice(idx, 1);
array.unshift(num);
}
}
return array;
};
log(moveZeroes(numbers));

Index Values SumUp to Total

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

how to check each element in an array for a specific condition

I have six integers stored in an array:
[2,3,4,5,6,7]
I would like to use each item in the array to check against a range of other integers 100 - 999 (i.e. all three-digit numbers) to find a number that has a remainder of 1 when divided by all the items in the array individually.
I'm not sure what javascript method to use for this. I'm trying a for loop:
function hasRemainder() {
let arr = [2,3,4,5,6,7];
for (i = 100; i < 999; i++) {
if (i % arr[0] == 1) {
return i;
}
}
}
but it has several problems I need to solve.
Instead of referring to a particular item e.g. arr[0], I need to find a way to loop through all the items in the array.
Currently, this function only returns one number (the loop stops at the first number with a remainder), but I need all the possible values in the given range.
If anyone could help with these two problems, I'd really appreciate it. Thanks.
You could map an array of values and then filter the array by checking every remainder value with one.
function hasRemainder() {
var array = [2, 3, 4, 5, 6, 7];
return Array
.from({ length: 900 }, (_, i) => i + 100)
.filter(a => array.every(b => a % b === 1));
}
console.log(hasRemainder())
This works also;
function hasRemainder() {
const arr = [2, 3, 4, 5, 6, 7];
const remainders = []
for (i = 100; i < 999; i++) {
const isRemainder = arr.every(numb => i % numb === 1)
if (isRemainder) {
remainders.push(i)
}
}
return remainders
}

How to remove specific number values in the array javascript [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
So im trying to remove the numbers 1,2,7,14 in the array but i dont know how to remove it. I did not find any solution that is similar to this
function mySelect(){
var prime1 = document.getElementById('input1').value;
var prime2 = document.getElementById('input2').value;
var n = prime1 * prime2;
console.log(n);
var foo = new Array(n);
console.log(foo.length);
var range = [];
for(var i=1;i<foo.length;i++){
range.push(i);
}
console.log(range);
// --------------------------------------------//
var half = Math.floor(n / 2), // Ensures a whole number <= num.
str = '1', // 1 will be a part of every solution.
i, j;
// Determine our increment value for the loop and starting point.
n % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
n % i === 0 ? str += ',' + i : false;
}
str += ',' + n; // Always include the original number.
console.log(str);
}
After you pushed the values to the array you can use a filter function, like so:
let nonos = [ 1, 2, 7, 14 ];
range = range.filter((element) => !nonos.includes(element));
This code specifies the values you want removed inside an array and then runs a loop on your original array and checks whether the element you're on is included in your nonos array and if it is, don't include it in your original array, else do.
To remove all instances of the provided numbers from an array:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeNumbers(array, ...numbers) {
numbers.forEach((number) => {
var index = array.indexOf(number);
while(index >= 0) {
array.splice(index, 1);
index = array.indexOf(number);
}
});
}
removeNumbers(array, 3, 2, 5, 7);
console.log(array);
find the index first and then apply splice method.
var array=[1,2,3,4,5,6,7,8,9,10]
console.log(array)
find the index of value you want to delete
let indexa=array.indexOf(2);
apply splice method to delete 1 value from applied index
array.splice(indexa,1);
console.log(array)

print out only even numbers

The Problem:
Create a program that prompts for a list of numbers, separated by spaces. Have the program print out a new list containing only the even number.
Convert the input to (a array). Many languages can easily convert strings to arrays with a built in function that splits apart a string based on a specified delimiter.
Write your own algorithm- don't rely on the language's built-in filter or similar enumeration feature.
Use a function called "filterEvenNumbers" to encapsulate the logic for this. The function takes in the old array and returns the new array.
All my notes on this:
//global array
var arr = [];
var arr = prompt("Enter your numbers");
// var eachNumber = arr.split(",");
var res = arr.split("");
console.log(arr);
console.log(res);
if(res = )
// var str = "How are you doing today?";
//push elements into array
// arr.push(prompt("Enter in a bunch of numbers", "")); //push input to array
// console.log(arr);
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
// var arr = prompt("Enter your numbers").split(",");
// console.log(arr);
// var arr = [];
// for(var i = 0; i < 10; i++)
// arr.push(prompt("Enter a number");
// Convert number into array in Javascript
// https://stackoverflow.com/questions/20730360/convert-number-into-array-in-javascript
// var numbers = "1, 2, 3";
// var eachNumber = numbers.split(",");
// /* now parse them or whatso ever */
// console.log(eachNumber);
// JavaScript Array filter
// http://www.diveintojavascript.com/core-javascript-reference/the-array-object/array-filter
// The JavaScript Array filter method iterates over each value of an array passing it to a callback function.
// If the callback function returns true, the current value is then pushed into the resulting array.
// The callback function is invoked with three arguments: the value of the element, the index of...
// the element and the Array object being traversed.
// Bellow is an example of filtering odd and even numbers out of an array:
// var arr = [1, 2, 3, 4, 5];
// var odd = arr.filter(function(val) {
// return 0 != val % 2;
// });
// // odd = [1, 3, 5]
// var even = arr.filter(function(val) {
// return 0 == val % 2;
// });
// even = [2, 4]
// console.log(even);
// The Array filter method can also be used to remove empty, null or undefined elements from an array:
// var arr = [0, null, 42, undefined, "", true, false, NaN, "", "foo bar"];
// var filteredArr = arr.filter(function(val, num) {
// return !(val === "" || typeof val == "undefined" || val === null );
// });
// // // filteredArr = [0, 42, true, false, NaN, "foo bar"]
// console.log(filteredArr);
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
b = [];
for (var i = 0; i < a.length; ++i) {
if ((a[i] % 2) === 0) {
b.push(a[i]);
}
}
This is an example of an array that finds and pushes the even numbers into another array. You can easily change it, and it wont push it to the another array, but instead will print even numbers. It will help you solve your problem
Is there a part of the question you do not understand? What are you having trouble with?
In order to prompt for user input you can use window.prompt('Enter a list of numbers separated by spaces');
This way of receiving user input will return a string. Since you are not allowed to use built-in methods for turning this into a list, one approach you can take is :
Store the user input into a variable
Iterate through each character in the string. Have a variable currentInteger defined that holds the digits of the current number you are looking at in your string (remember: numbers can be longer than a single digit, so when iterating through the string your current number may not be represented by the single character you are looking at)
once you reach a space, you know that the currentInteger has been completed, append that to a new list IF it is an even integer.
Since your currentInteger variable is a string, you will need to use parseInt() to make it a number and check if it is even.

Categories