Jquery function consumes the array - javascript

I don't quite understand what's wrong with my function that I wrote,
When I pass an array to it, eg:
var pvars=['health/1/1.jpg','health/1/2.jpg','health/1/3.jpg','health/1/4.jpg'];
cache_threads(pvars,1);
Then I end up with an empty variable, eg:
alert(pvars);
Returns an empty string.
Here is my function:
var cache_threads=function (arruy,quant){
if (quant==undefined) quant=1;
var div=Math.ceil(arruy.length/quant);
var a = arruy;
while(a.length) {
cache_bunch(a.splice(0,div));
}
}

a and arruy are the same array.
When you .splice one, you'll be splicing the other one, too!
If you want a (shallow) copy of the array, use .slice():
var a = arruy.slice(0);

Related

Return an Array of Abbreviated Strings with .filter() - JavaScript

If I have an array of strings that I would like to abbreviate with the filter() method.
How would I use filter() in combination with str.substring (or another string method if applicable)?
In the following code I would like to return the first four characters of each name, but it doesn't seem to be working.
JavaScript
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.filter(function(name){
return name.str.substring(0,4);
});
You should use map:
const poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth", "H"];
const nickNames = poshNames.map(name => name.substring(0,4));
console.log(nickNames);
Use map instead of filter
and it will work:
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.map(function(name) {
return name.substring(0,4);
});
What filter does is essentially return an array that contains every element in the array for which the function returns true.
What map does, on the other hand, is return an array that contains the value the function returns for every value in the array.
Note: Both methods return a new array without affecting the original.

Count the recurrence of a word

I am writing a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
function countWords(str) {
var obj = {};
var split = str.split(" ");
return split;
}
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> MUST RETURN {ask: 1, a: 2, bunch: 2, get: 1}
Have any idea?
I wont give you finished code ( thats not the sense of a homework) , but i try to get you to solve the problem on your own.
So far you've already got an array of words.
Next lets declare an object we can assign the properties later.
Then we'll iterate over our array and if the array element doesnt exist in our object as key yet ( if(!obj[array[i]])) well create a new property, with elements name and the value 1.( obj[array[i]=1; )
If the element is a key of that object, lets increase its value.
( obj[array[i]]++;)
Then return the object.
So you could use a javascript Map for this like so:
var myMap = new Map();
myMap.set(keyString, count);
and access the value of the key like so:
myMap.get(keyString);
For more information you can read up here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

Dynamically instantiate class in javascript

I checked out this reference link and ended up using Matthew's solution, as it works for me.
var factory ={};
factory.Tree = function(arg1,arg2,arg3,arg4){
console.log(arg1+""+arg2+""+arg3+""+arg4);
}
function instantiate(classname){
return new (function(a){ return factory[classname].apply(this,a);})(Array.prototype.splice.call(arguments,1));
// also is this ^^^ a good practice? instead of declaring the temp function beforehand
// function t(a) {return factory[classname].apply(this,a);}
// return new t(Array.prototype.splice.call(arguments,1));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
Though, I'm not sure why using user123444555621's solution only works if I pass in "arguments" (that is everything including "classname"):
function instantiate(classname){
return new (Function.prototype.bind.apply(factory[classname], arguments));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
but if I slice "arguments" and remove "classname", then pass in the result array, it does not work as expected:
function instantiate(classname){
var args = Array.prototype.splice.call(arguments,1);
// ^^ I checked and this prints 1,2,3,4 as well
return new (Function.prototype.bind.apply(factory[classname], args));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 234undefined
I'm not sure why but somehow it seems like the args array is sliced (again) and removes its first element (1 in this case).
Could someone offer any insights? Thanks
Did you use the right array function slice vs splice ?
Array.prototype.slice() - Creates a new array from elements of an existing array. It does not modify the original array.
Array.prototype.splice() – Deletes and/or inserts elements in an array. Unlike slice(), the splice() method modifies the original array
and returns a new array. The splice() method takes three arguments.
Your problem is this line
var args = Array.prototype.splice.call(arguments,1);
You have essentially removed the first item from the arguments while turning it into array args
simply replace 1 by 0
var args = Array.prototype.splice.call(arguments,0);
DEMO
var factory ={};
factory.Tree = function(arg1,arg2,arg3,arg4){
console.log(arg1+""+arg2+""+arg3+""+arg4);
}
function instantiate(classname){
var args = Array.prototype.splice.call(arguments,0);
return new (Function.prototype.bind.apply(factory[classname], args));
}
instantiate("Tree",1,2,3,4);

pass array to method with condition

Im using the following code to split array which is working,
I need to pass some value when array
for examle here is split the value to array
var myArr = val.split(/(\s+)/);
and if array in place 2 is empty I need to use the method like following
pass empty array in second arg
var val = process.run(myArr[0], [], options);
if the array place 2 is not empty I need to pass it like following
var val = process.run(myArr[0], [myArr[2]], options);
The second arg is array inside arry with the value of 2
there is nice way to do it instead of if on the method ?
I would create a function, as Dave Newton recommends. I could take the initial val and options as an argument and return the result of process.run:
function runProcess(val, options) {
var myArr = val.split(/(\s+)/);
var argArray = [];
if(myArr[2]) {
argArray.push(myArr[2]);
}
return process.run(myArr[0], argArray, options);
}
Since I don't know what the function exactly does, the name of the function and variables are pretty arbitrary. Feel free to change them to your needs.
If myArr[2] is a flat array and will always be flat, why not...
var val = process.run(myArr[0], [].concat(myArr[2]), options);

Why pushing array into another array merges the elements instead of putting them in separate array

I have a array into which I push new values iteratively, at the end of each iteration I want the array formed to be inserted into new array.
Ex: if at the end of first iteration array=[1,2,3,4], then bigarray=[[1,2,3,4]].
After 2nd iteration, if array=[5,6,7,8], then bigarray=[[1,2,3,4],[5,6,7,8]] and so on.
So basically bigarray is to contain a list of arrays out of which I can obtain arrays.
ex: bigarray[0] should give me a array [1,2,3,4]
What I am doing now is array.push(some values) and at the end bigarray.push(array). Doing this merges all the values into a single array like this
bigarray=[1,2,3,4,5,6,7,8] out of which I can separate first array and second array.
piece of code:
var array=[];
for(var i=0; i<range;i++){
var arraychart=[];
var jan= resp.ChartDataList[i].jan;
arraychart.push(jan);
var feb= resp.ChartDataList[i].feb;
arraychart.push(feb);
var mar= resp.ChartDataList[i].mar;
arraychart.push(mar);
var apr= resp.ChartDataList[i].apr;
arraychart.push(apr);
var may= resp.ChartDataList[i].may;
arraychart.push(may);
var jun= resp.ChartDataList[i].jun;
arraychart.push(jun);
//var jan= resp.ChartDataList[i].jan;
array.push(arraychart);
alert (arraychart);
}
alert(array);
How do I achieve the above desired result??
You should call array.push in this way (array.push([1,2,3])) instead of (array.push(1,2,3))
var bigarray = [];
bigarray.push( [1,2,3,4] );
bigarray.push( [5,6,7,8] );
console.log(bigarray); // prints [[1,2,3,4],[5,6,7,8]]
EDIT
After seeing your code, you don't have problems in your code, just print the array using console.log instead of alert, because alert will call .toString() of the big array, and flatten it
U can try something like this
bigArrray[bigArray.length] = subArray
But...
bigArrray.push([1,2,3])
...works as well for me

Categories