Filling an array with an identical function [duplicate] - javascript

This question already has answers here:
Functional approach to basic array construction
(5 answers)
Closed 8 years ago.
I'm trying to create a function that returns an array with n elements, that are all the same function (this array will later be used to call those functions in parallel using async).
I can easily loop over an array and add the function to each element, but was wondering if I can do it in one line, using map:
//the function to point to
var double = function(x) {
return x*2;
};
//this function will create the array - just a filler for a one-liner
var createConsumersArray = function(numOfConsumers) {
var consumers = (new Array(2)).map(function(x){return double;});
return consumers;
};
var t = createConsumersArray(2);
console.log(t); //prints [,]
console.log(t[1](2)); //TypeError: Property '1' of object , is not a function
If I pre-fill the array with constants, the map works, i.e.:
var x = [1,2,3];
console.log(x.map(function(x){return double;})); //prints [ [Function], [Function], [Function] ]
console.log(x[1](2)); //prints 4
How can I accomplish filling an array with an identical function in the shortest way?

You have to change a little.
var createConsumersArray = function(numOfConsumers) {
var consumers = Array.apply(null, Array(numOfConsumers)).map(function(){return double;});
return consumers;
};

This is more functional programming. If you'd like to program in this style, I'd recommend you look at underscore.js. Here's an example of a range function:
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
For your use case you would do:
_.map(_.range(4), function(num){ return double; });
Here's the corresponding jsfiddle example:

Related

Passing iterator to a function's parameter [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 2 years ago.
I wrote a Javascript function and a loop whose role is to call my function, each time with a different parameter. My idea was that the iterator will help me use a different variable each time but obviously this doesn't work. I figured out that my problem is that when the loop calls the function, the parameter is a string rather than an object name. Any way to save that or the idea was flawed from the beginning?
var a0 = [1,2,3];
var a1 = [4,5,6];
var a2 = [7,8,9];
function myFunction (parameter) {instructions;}
for (i=0; i<3; i++)
myFunction("a"+i);
You could wrap the arrays in an array and iterate this array.
function myFunction(reference) {
console.log(...reference);
}
let a0 = [1, 2, 3],
a1 = [4, 5, 6],
a2 = [7, 8, 9];
for (const array of [a0, a1, a2]) myFunction(array);

In JS map() method, why can't callback function parameters compute with each other? [duplicate]

This question already has answers here:
Array map function doesn't change elements
(4 answers)
Why does this map function not mutate the values in the original array?
(3 answers)
Closed 2 years ago.
The problem is that I cannot subtract each index of an array from its element(number), using the array.prototype.map() method. I expected the subtraction to be valid, but it is not.
Here is the code:
const whiteSp = [ 5, 11 ];
whiteSp.map(function (ele, i) {
console.log(ele, i) // 5 0, 11 1
console.log(ele - i) // 5, 10
ele = ele - i;
return ele;
});
console.log(whiteSp) // expected [ 5, 10 ], but got [ 5, 11 ]
The second console.log indicates the computation has been made as seen by the value 10, but returns 11 for some reason.
I have also tried 'return ele - i' without its above line, but still does not work.
Ciao, you could try something like this:
let whiteSp = [ 5, 11 ];
whiteSp = whiteSp.map((ele, i) => { return ele - i; });
console.log(whiteSp)
and remember that map function returns a new array so you have to do whiteSp = whiteSp.map....
You need an assignment of the mapped values.
const
whiteSp = [5, 11],
result = whiteSp.map((ele, i) => ele - i);
console.log(result);

Inserting an object so the array stays sorted

I have an enum of different Steps
export enum StepCategory {
START = 0,
POSITION_1 = 1,
TRANSPORT = 2,
RECEIVER = 3,
END = 4,
NO_STEP_MATCH = 5
}
This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:
var array = [{"END" , "POSITIVE"}]
Afterwards I would get the Info for Step 2, then I would have:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
But this is not sorted.
What should I do? Should I declare an array of 6 undefined values
var array = [undefined, undefined, undefined, undefined, undefined, undefined]
This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.
Just some small Info: I use AngularJS 1, Typescript and Lodash
In plain Javascript, you could sort it with an object and the assigned values of the key.
var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4, NO_STEP_MATCH: 5 },
array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];
array.sort(function (a, b) {
return StepCategory[a[0]] - StepCategory[b[0]];
});
console.log(array)
First of all, this is - as someone mentioned in the comments - not syntactically correct:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:
var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]
In order to sort this with LoDash you could use something like this:
var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);
This sorts your array by the value of the first key of each object which refers to your enum value.

JavaScript Array Prototype, 'this' doesn't have the 'push' method [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I have tried this:
// You can pass an array on the addArr method, and each element from the
// passed array is pushed to the array on which addArr was called.
Array.prototype.addArr = function( arr ){
console.log( this );
// As `this` is the array, we use this.push to insert arr's elements
arr.forEach(function(elm){
this.push( elm );
});
// And then finally return this.
return this;
};
The code has been explained using comments, but let me put in straight. I am trying to create a new method on the Array object called addArr, which can pass an array [1, 2, 3] to the method and each of the element is added to the array on which the method was called.
For e.g
var myArr = [1, 2, 3];
myArr.addArr( [4, 5, 6] );
// The output is supposed to be [1, 2, 3, 4, 5, 6]
I am getting Uncaught TypeError: this.push is not a function, I have tried debugging, this always returns the parent array still it says that push is not a function.
How can I solve it? I could use libraries like Lodash for these, but I don't prefer to for such a small application.
Thanks!
Store this into a variable outside of the function.
Array.prototype.addArr = function( arr ){
var that = this;
arr.forEach(function(elm){
that.push( elm );
});
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
Alternative, as #nnnnnn pointed out, you could pass this as an argument to the .forEach function.
Array.prototype.addArr = function( arr ){
arr.forEach(function(elm){
this.push( elm );
},this);
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);

Swapping two items in a javascript array [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript swap array elements
I have a array like this:
this.myArray = [0,1,2,3,4,5,6,7,8,9];
Now what I want to do is, swap positions of two items give their positions.
For example, i want to swap item 4 (which is 3) with item 8 (which is 7)
Which should result in:
this.myArray = [0,1,2,7,4,5,6,3,8,9];
How can I achieve this?
The return value from a splice is the element(s) that was removed-
no need of a temp variable
Array.prototype.swapItems = function(a, b){
this[a] = this.splice(b, 1, this[a])[0];
return this;
}
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
alert(arr.swapItems(3, 7));
returned value: (Array)
0,1,2,7,4,5,6,3,8,9
Just reassign the elements, creating an intermediate variable to save the first one you over-write:
var swapArrayElements = function(arr, indexA, indexB) {
var temp = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = temp;
};
// You would use this like: swapArrayElements(myArray, 3, 7);
If you want to make this easier to use, you can even add this to the builtin Array prototype (as kennebec# suggests); however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types):
Array.prototype.swap = function(indexA, indexB) {
swapArrayElements(this, indexA, indexB);
};
// You would use this like myArray.swap(3, 7);
Note that this solution is significantly more efficient than the alternative using splice(). (O(1) vs O(n)).
You can just use a temp variable to move things around, for example:
var temp = this.myArray[3];
this.myArray[3] = this.myArray[7];
this.myArray[7] = temp;
You can test it out here, or in function form:
Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
Then you'd just call it like this:
this.myArray.swap(3, 7);
You can test that version here.

Categories

Resources