How to create an array with 'a' repeated 'b' times [duplicate] - javascript

This question already has answers here:
Create an array with same element repeated multiple times
(25 answers)
Closed 2 years ago.
I am trying to create a function that takes in two vairables a and b, this function will create an array with variable a reapeated b times.
This is how far I have gone but It's not outputting th correct number of items in the array:
var createArr = function(a, b) {
// returns an array with variable a repeated b times.
if (typeof b == 'number') {
var arr = [];
for (var i = 0; i <= b; i++) {
arr.push(a);
};
}
return arr;
};
createArr("ready",3)

Easy:
function createArr(a, b) {
return Array(b).fill(a);
}

If you use <= and the value “3” for “b”, the loop will run once for 0, 1, 2, and 3. Oops, that’s 4 times.
Instead you want to use < so the loop will run once for 0, 1, then 2, and not for 3.
See also https://en.wikipedia.org/wiki/Fencepost_error

for loop, break will be < not <= because when <= for loop start with 0 and break when it 3 so loop 4 times when need to loop 3 times so need an use <
var createArr = function(a, b) {
// returns an array with variable a repeated b times.
if (typeof b == 'number') {
var arr = [];
for (var i = 0; i < b; i++) {
arr.push(a);
};
}
return arr;
};
console.log(createArr("ready",3));

Related

Javascript function invoke with different invoke fashions [duplicate]

This question already has answers here:
How can I make var a = add(2)(3); //5 work?
(33 answers)
Closed 5 years ago.
I want to implement the function in javascript let say Add that should support bellow formats
add(a,b,c)
add(a)(b)(c)
add(a)(b,c)
add(a,b)(c)
All these should return a+b+c. Is it possible? if so how?
Whenever the function is run collect the arguments object parameters into an array, and check it's length. If the length of the array is 3 or greater sum the first 3 numbers using Array#reduce. If not, return the function.
function add() {
var args = []; // collect the arguments
function innerAdd() {
args.push.apply(args, arguments); // add the arguments to args
// if the length of args is under 3 return innerAdd, if not sum the first 3 numers
return args.length < 3 ? innerAdd : args.slice(0, 3).reduce(function(s, n) {
return s + n;
});
}
return innerAdd.apply(null, arguments); // invoke innerAdd with current arguments
}
var a = 1, b = 2, c = 3;
console.log(add(a,b,c));
console.log(add(a)(b)(c));
console.log(add(a)(b,c));
console.log(add(a,b)(c));
You can do something like
function add(){
let sum = 0;
for(let e of arguments) sum += e;
let ret = add.bind(null, sum);
ret.toString = () => sum;
ret.valueOf = () => sum;
return ret;
}
let x = +add(2, 3)(4)(11)
console.log(x, typeof x);

Check if element is in array twice time [duplicate]

This question already has answers here:
Finding out how many times an array element appears
(6 answers)
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
I need to know if an element is in array twice or many time.
var arr = [elm1,elm2,elm3,elm3,elm4,elm5,elm5,elm5,elm6,elm7] ;
if(elm is in array by many time ){
// do some code with this element
}else{
// other stuff ;;
}
Any suggestions ?
The countInArray function may be an option for you
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
Or something like this, this may be better for you to understand the code and adjust somethings where you want to! :
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
function check(){
var arr =['1','2','3','3','4'];
for (i=0; i<arr.length;i++){
for (x=0;x<arr.length;x++){
if(arr[i]==arr[x] && i != x){
console.log('SAME ones in ARRAY: '+arr[i]);
}else console.log('no same ones');
}
}
}

JavaScript - for Loop vs. Array shift

I have two functions, they do look alike but what I don't really understand is when inside the for-loop, since the input is an array, why doesn't the array need any index to call the first array?
I have an array of...
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
I'm trying to loop through the array with an input. The result of the first function will then be used as the next function's input then the first array will be removed.
This is what I wrote...
function applyAndEmpty(input, queue)
{
var length = queue.length;
for(var i = 0; i < length; i++)
{
input = queue[0](input);
queue.shift();
}
return input;
}
The above does give me the answer but then I see that there's another way of writing it which is
var applyAndEmpty = function(input, queue)
{
var length = queue.length;
for(var i = 0; i < length; i++)
{
input = queue.shift()(input);
}
return input;
};
What I don't understand is the part input = queue.shift()(input).
Doesn't the queue need an index?
So you're basically asking what shift does and here you go:
What you can do using for(var i=0;... you can do using shift() (quite similar but not!)
Using for loop (and index)
var array = [
function(){return "a";},
function(){return "b";}
];
for(var i=0; i<array.length; i++){
console.log( array[i]() );
// "a"
// "b"
}
console.log(array.length); //2 !!Still there!!!
Using shift() (and while for example)
var array = [
function(){return "a";},
function(){return "b";}
];
while(array.length){ // while array has length
console.log( array.shift()() ); // execute and remove from array
// "a"
// "b"
}
console.log(array.length); //0 !!!Empty array due to shift()!!!
So basically it removes a key from your Array and returns it.
As long as that array has keys it will loop until it's empty.
The difference between the two is drastic:
The for loop in example 1. will loop but not alter your original array.
Using shift() in example 2. you're (using and) removing your Array keys one by one.
Read more about Array manipulation:
Array.prototype.shift 1 <-- [2,3,4]
Array.prototype.unshift 5 --> [5,2,3,4]
Array.prototype.push [5,2,3,4,6] <-- 6
Array.prototype.pop [5,2,3,4] --> 6
and other Methods
You can simplify the logic using Array.reduce
Here how you can do that:
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
function runPuzzler(inputValue){
return puzzlers.reduce(function(prev, curr){
return curr(prev);
},inputValue);
}
Output :
EachArrayValues::100
EachArrayValues::200
EachArrayValues::0
EachArrayValues::400
EachArrayValues::500
EachArrayValues::-50
Negative value found, ie -50

Javascript array return is adding double quotes?

Here is my code:
function iLoveThree (array) {
var threes = [];
var x;
for (x in array) {
if (x % 3 == 0) {
threes.push(x)
}
}
return threes
}
When I pass the array [1,2,3,4,5,6,7,8,9] I get the following:
Function returned
["0","3","6"]
instead of
[3,6,9]
My question is, where are these double quotes coming from?
for...in is a bad way of iterating array indices. Better use filter:
[1,2,3,4,5,6,7,8,9].filter(function(x) {
return x % 3 == 0;
}); // [3, 6, 9]
A for..in loop does not loop through the array elements, it loops through the indices of the array. So for:
var arr = ["a", "b", "c"]
for ( x in arr ) console.log( x );
You'll get the string keys of ["0", "1", "2"]
You can fix your code by replacing your loop with a native for loop:
for ( var x = 0; x < array.length; x++ ) {
if (array[i] % 3 == 0)
threes.push(array[i]);
}
So basically in x in array x is the index not the array value. Because anyway 0 is not in the array but your function is returning it as well. You should instead access the values using array[x]
There are various approaches, one of them is using .filter
function iLoveThree(array){
return array.filter(function(x){
return (x%3==0?1:0);
});
}
Or
function iLoveThree (array) {
var threes = [];
var x;
[].forEach.call(array, function(x){
if (x % 3 == 0) {
threes.push(x)
}
}
return threes
}
You're using a for..in loop which gives you the keys in an object, or in this case and array. Keys are always strings. Instead, you want to use a standard for loop.
for (var i = 0; i < array.length; i++) {
var x = array[i];
if (x % 3 === 0) {
threes.push(x);
}
}
Or if you want to use a more functional approach, you could use Array.prototype.filter.
return array.filter(function(x) {
return x % 3 === 0;
});
Not an answer to your question directly, but here's a nice way to pull every multiple of 3 from an array of numbers:
[1,2,3,4,5,6,7,8,9].filter(item => item % 3 === 0)
It seems that you are pushing in the indexes and not the actual values, go ahead and try the following:
function iLoveThree(array) {
var threes = [];
var x;
for (x in array) {
if (((x-2) % 3) == 0) {
threes.push(array[x])
}
}
return threes;
}
Another option, shorter, is:
function iLoveThree(arr) {
var threes = [];
for (var i = 2; i < arr.length; i = i + 3) {
threes.push(arr[i]);
};
return threes;
}
if you are comfortable with callback/predicate based loops, you could make stuff even shorter by filtering the array, instead of creating a new one:
function iLoveThree(arr) {
return arr.filter(function(x) {
return (x % 3) == 0;
});
}
Before you read the answer below, please read: Why is using “for…in” with array iteration such a bad idea? (Thanks to #Oriol for this link.)
Douglas Crockford has also discouraged the use of for..in. He recommends using array.forEach instead.
function iLoveThree (array) {
var threes = [];
array.forEach(function(item, i){ // use forEach, 'item' is the actual value and 'i' is the index
if (item % 3 === 0) {
threes.push(item); // you missed ; here
}
});
return threes; // you missed ; here
}
console.log(iLoveThree([1,2,3,4,5,6,7,8,9]));
Read up: Array.prototype.forEach() | MDN
If you read the for...in documentation, you will realize that you are pushing to threes the indexes (also called keys) not the values, because the variable x represents the index, so the value should be accessed by array[x].
function iLoveThree (array) {
var threes = [];
for (var x in array) {
if (array[x] % 3 == 0) {
threes.push(array[x])
}
}
return threes
}
There are several ways to achieve this, the best one is by using a filter, but that way was already explained by someone else, therefore I will use an exotic implementation using a reduce
[1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(function(acc, e){return e % 3 == 0 ? acc.concat(e) : acc}, [])
Outputs 3, 6, 9

Count occurrences of array elements with JavaScript [duplicate]

This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?
This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.
I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}
var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]

Categories

Resources