Here is the code I have. I am pretty new to javascript still so I don't see why adding the function stops the for statement from incrementing the integers.
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (const i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Any help would be greatly appreciated.
I ran your code under Node.js:
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (const i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
incr.js:6
for (const i = 0; i < arr.length; i++){
TypeError: Assignment to constant variable.
at incrementByOne (incr.js:6:37)
$
As you can see, it complains that you are trying to change the value of i which your code said was constant. Write let i = 0 for a non-constant value.
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
[ 11, 11, 17, 13 ]
$
You could use map also:
const incrementByOne = (arr) => arr.map((element) => element + 1);
You should use let i = 0 instead of const i= 0 to initilize the loop iteration counter i
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Then call incrementByOne function
incrementByOne(arr);
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
let a = incrementByOne(arr)
console.log(a)
Related
// sorting an array
const least_num = (arr)=>{
let smallest = arr[0];
let smallest_index = 0;
for(let i=1; i<arr.length;i++){
if (arr[i] < smallest) {
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index
}
const sortArray = (arr)=>{
const newArr = [];
for(let i in arr){
let smallest = least_num(arr);
console.log(smallest,i)
console.log(arr.splice(smallest,1),arr)
}
return newArr;
}
console.log(sortArray([5,4,3,2,1]));
I am trying to sort array without sort().
It stuck at array length of 2.
It may because of for loop. And how to remove element in a array using index.
A few issues:
The code never adds anything to newArr, so the function always returns an empty array. It should add the removed (spliced) element to newArr. This can be done with newArr.push(...arr.splice(smallest,1))
The for..in loop will iterate fewer times than expected, because in each iteration the array gets shorter, thereby removing future iterations for the loop. As the idea is to remove all items from the array, just keep looping until the array is empty with while (arr.length)
With these two corrections, your code works:
const least_num = (arr)=>{
let smallest = arr[0];
let smallest_index = 0;
for(let i=1; i<arr.length;i++){
if (arr[i] < smallest) {
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index
}
const sortArray = (arr)=>{
const newArr = [];
while(arr.length) {
let smallest = least_num(arr);
console.log(smallest)
newArr.push(...arr.splice(smallest,1));
console.log(arr)
}
return newArr;
}
console.log(sortArray([5,4,3,2,1]));
You can also try this.
const sortArray = (arr)=>{
let originalArr = [...arr];
var sortArr = [];
while(originalArr.length) {
let val = originalArr[0];
for ( let j = 1; j < originalArr.length; j++ ) {
if(val>originalArr[j]) {
val = originalArr[j];
}
}
sortArr.push(originalArr.splice(originalArr.indexOf(val), 1)[0]);
}
return sortArr;
}
console.log(sortArray([5,4,3,2,1]));
I wanted to create a function, that counts all unique Items in an array, but somehow I do not get any output.
This is my array!
let arr = ["hi", "hello", "hi"];
And this is the code I wrote so far:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
countUnique(arr);
}
console.log(countUnique(arr));
Your are counting values correctly, however then you are calling this method recursively countUnique(arr); and it results an error of call stack exceeded.
So just remove recursive call of method countUnique(arr); and return counted value counts:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
return counts;
}
let arr = ["hi", "hello", "hi"];
console.log(countUnique(arr));
JavaScript engine limits the maximal recursion depth. We can rely on it being 10000, some engines allow more.
You could take a Set and return the size.
const countUnique = array => new Set(array).size;
console.log(countUnique(["hi", "hello", "hi"]));
let arr = ["hi", "hello", "hi"];
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
if(arr[i] in counts) {
counts[arr[i]]++;
} else {
counts[arr[i]] = 1;
}
}
return Object.keys(counts).length;
}
console.log(countUnique(arr));
how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232
I have this array [1,2,3]
I would like to be able to set its length to 7
and have this [1,2,3,1,2,3,1] as a result.
Anyone?
const arr = [1,2,3];
// Something like
arr.resize(7);
console.log(arr); // [1,2,3,1,2,3,1]
EDIT:
Based on chevybow answer below i wrote this functions to serve my needs.
// Immutable
Array.prototype.resize = function(size) {
const array = Array(size);
for(let i = 0; i < size; i++) {
array[i] = this[i%this.length];
}
return array;
}
// Mutable
Array.prototype.resize = function(size) {
const array = this.slice(0);
this.length = size;
for(let i = 0; i < size; i++) {
this[i] = array[i%array.length];
}
}
Are those ok? or you think that putting it on the chain is not a good idea, if so why?
You can use modular arithmetic to loop through up to the length of your final array and then use the index to basically loop through and push that onto a new array
Using the current array value % array.length will get you the current position of the array by progressing it in a circular motion
let num = 7;
let array = [1,2,3];
let result = [];
for(let i = 0; i < num; i++){
result.push(array[i%array.length]);
}
console.log(result)
A simple while loop would suffice:
function repeat(arr, toLength) {
let output = [...arr];
while (output.length < toLength) output = [...output, ...arr];
return output.slice(0, toLength);
}
console.log(repeat([1, 2, 3], 7));
console.log(repeat([1, 2, 3], 2));
How about this version:
const nums = [1, 2, 3];
function resize(arr, length) {
let position = 0;
return Array.from(Array(length)).reduce((acc, _, i) => {
return acc.concat(arr[i % arr.length]);
}, []);
}
console.log(resize(nums, 7));
I know it's a stupid question, but I only learning programming 3 months now.
How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?
Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed
I got this so far, but I think It's a dead end...
const array = [1, 2, 3, 3, 1];
const removeDuplicate = () => {
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i != j) {
if (array[i] == array[j]) {
shortArray[index] += array[i]
console.log(array[i]);
}
}
}
}
return shortArray;
}
console.log(removeDuplicate());
return this:
1
3
3
1
[ NaN ]
thanks!
Use an object as a helper. If a value appears in the helper, it's not unique and can be ignored. If it's not in the helper it's unique, push it into the result array, and add it to the helper object.
const array = [1, 2, 3, 3, 1];
const removeDuplicate = (arr) => {
const helperMap = {};
const result = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (!helperMap[item]) {
result[result.length] = item;
helperMap[item] = true;
}
}
return result;
};
console.log(removeDuplicate(array));
function unique(arr) {
var obj = {};
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
obj[value] = true; // set as key
}
return Object.keys(obj); //return all keys
}
Use below function:
function RemoveDuplicate(array){
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
let exist=false;
for(let j=0;j<shortArray.length;j++){
if(array[i]==shortArray[j]){
exist=true;
break;
}
}
if(!exist){
shortArray[shortArray.length]=array[i];
}
}
return shortArray;
}