I need to create a Javascript Function to create custom push function - javascript

I am building JavaScript code to make a custom push function. My new function should act exactly like the original push function.
Here is the code. Please check it.
<script type="text/javascript">
function MyArray(){
this.add=function(x){
return this[this.length]=x;
}
}
MyArray.prototype=Array.prototype;
var collection = new MyArray();
collection.push(44);
collection.add(56); // this is not working.
collection.push(77);
collection.push(88);
console.log(collection);
</script>

Because you're not using a native array, the length property doesn't automatically adjust itself. You need to increment it manually, otherwise the next push will just overwrite it:
function MyArray(){
this.add=function(x){
return this[this.length++]=x;
}
}

If you want to use add instead of push (so, use add as push-alias), just refer to the original Array.prototype.push. See snippet. The snippet also contains a custom addMulti method, derived from Array.prototype.push.
function MyArray(){ }
MyArray.prototype = Array.prototype;
MyArray.prototype.add = Array.prototype.push;
// custom addMulti method, derived from Array.prototype.push
MyArray.prototype.addMulti = function addMulti(arrayOfValues){
[].push.apply(this, arrayOfValues);
};
var foo = new MyArray;
// add and push both work
foo.add(13);
foo.push(17);
foo.add(15,16,18);
foo.push(112);
// push an array of values
foo.addMulti([200,300,400,500]);
var report = new MyArray;
report.add('<code>foo.length: ',foo.length, ', foo: [', foo, ']</code>');
document.querySelector('#result').innerHTML = report.join('');
<div id="result"><div>

Related

How do i append an array to an already existing state array?

Trying to implement pagination using react but cannot seem to figure out a way to append the new response to an already existing state variable.
I'm trying to implement a load more functionality wherein the data is appended to the list itself.
const handleLoadMoreClick = () => {
let tempObj = postparem;
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
getProductChildMenu(APIProductList, postparem);
setCopyMenu(...copyMenu, productChildMenu);
};
Currently the map function is running iterating over productChildMenu so it replaces the data but i want to append the data in productChildMenu to copyMenu.
I tried iterating over productChildMenu and pushing each element to copyMenu but it is coming out undefined or if i push it completely at once, it creates a 2d array which does not iterate in map correctly.
You must do the following to merge 2 objects into your state.
const handleLoadMoreClick = () => {
...
...
setCopyMenu({...copyMenu, ...productChildMenu});
};
You cannot do what you are doing with tempObject here:
let tempObj = postparem;
// this is wrong.
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
Even though you call the variable tempObj a "temporary object", it is not a new object. It is just a reference to the object stored in the variable postparem.
So your code is identical to the (equally wrong) postparem.pagenumber = postparem.pagenumber + 1.
Instead, you really have to create a new object:
let tempObj = {
...postparem,
};
and then you can either modify that, or already introduce your change on object creation.
That would look like
let tempObj = {
...postparem,
pagenumber: postparem.pagenumber + 1,
};
setPostparem(tempObj);
Or even a bit shorter:
setPostparem({
...postparem,
pagenumber: postparem.pagenumber + 1,
});

Pushing an object into an object under a certain key

I'm trying to achieve the following Array/Object,
[
1:[{data:data},{data:data}]
]
How would this be achieved?
I got thus far,
var data = [];
data['1'] = {data:data}
but this just overwrites.
The notation [] is for making Arrays, {} is for making Objects.
See the following
const data = {}; // Initialize the object
data['1'] = []// Makes data={'1':[]}
data['1'].push({data: 'data'}) // Makes data = {'1':[{data:'data'}]}
OR
const data = []; // Initialize the Array
data.push([]) // Makes data=[[]]
data[0].push({data: 'data'}) // Makes data = [[{data:'data'}]]
If i get you right you want to push objects into an array inside of an hashtable ( which can be easily implemented using an object in javascript).
So we need an object first:
const lotteries = {};
Now before storing data, we need to check if the relating array exists, if not we need to create it:
function addDataToLottery(lottery, data){
if(!lotteries[lottery]){ //if it doesnt exist
lotteries[lottery] = []; //create a new array
}
//As it exists definetly now, lets add the data
lotteries[lottery].push({data});
}
addDataLottery("1", { what:"ever"});
console.log(lotteries["1"]));
PS: If you want to write it in a fancy way:
class LotteryCollection extends Map {
constructor(){
super();
}
//A way to add an element to one lottery
add(lottery, data){
if(!this.has(lottery)) this.set(lottery, []);
this.get(lottery).push({data});
return this;
}
}
//Create a new instance
const lotteries = new LotteryCollection();
//Add data to it
lotteries
.add("1", {what:"ever"})
.add("1", {sth:"else"})
.add("something", {el:"se"});
console.log(lotteries.get("1"));

Array previous values getting overwritten in angularjs

I am trying to do the following, where foo is a function which fills the 'out' array.
But for each data centre in data centres object, pushed out array is getting overwritten by a new value.
I want to prevent this overwriting.
How to create a new array reference/ instance in a loop?
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(out);
});
Put your out declaration outside:
var out = [];
_.map(datacenters, function(datacenter){
foo(datacenter, out);
$scope.dcSelected.push(out);
});
I don't fully understand what you trying to do, so I will do a general example:
var datacenters = [1,2,3,4]
var out = []
datacenters.map(function(datacenter){
datacenter2 = datacenter + 1;
out.push(datacenter2);
});
console.log(out);
[ 2, 3, 4, 5 ]
(I used map that way because I haven't imported the underscore for js)
You may try angular.copy(out) of angularJs. Hope it ll work for you
_.map(datacenters, function(datacenter){
var out = []
foo(datacenter, out);
$scope.dcSelected.push(angular.copy(out));
});
You have 2 options:
1) create a closure
2) create another array as part of your controller, that will store linkage of data center and out an array, imagine it as a key, value but in a global variable of the same controller.

Angular JS copy Object to another into a for loop

Trying to copy a part of a json object into another json object (thats a filter), into a for loop, under a conditional statement, it doesn't work.
This work but a plain to write an array:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats.push(
{
"id" :omegaCandidats[i].id,
"prenom" :omegaCandidats[i].prenom,
"nom" :omegaCandidats[i].nom,
"heure" :omegaCandidats[i].heure,
"dateRdv" :omegaCandidats[i].date
}
)
};
};
This doesn't work, and that's what i want to do. Its logical and should work:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[i] = omegaCandidats[i];
};
};
This one work but only get one value of the for loop its useless:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[0] = omegaCandidats[i];
};
};
what about using a filter:
$scope.candidats = omegaCandidats.filter(function(candidat){
return candidat.dateRdv == date;
});
You can use filter array method, try this:
$scope.candidats = omegaCandidats.filter(function(item) {
return item.dateRdv==date;
});
I think this should work :
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
//$scope.candidats.push(omegaCandidats[i]);
$scope.candidats.push(angular.copy(omegaCandidats[i]));
//copy will create a new reference for your object.
};
};
The code you had is not logical to me :
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[i] = omegaCandidats[i]; // This can't work because $scope.candidats[i] is not defined.
// You would also have an inconsistent array
};
};

how to copy array to array

var ce_info=[
{location:"inchannel",name:"Jae Jung",volume:"50",url:"img/jae.jpeg",group:1},
{location:"inchannel",name:"Houston",volume:"50",url:"img/houston.jpeg",group:1},
{location:"inchannel",name:"Jun kuriha..",volume:"50",url:"img/jun.jpeg",group:1},
{location:"inchannel",name:"Andrea Melle",volume:"50",url:"img/andrea.jpeg",group:0},
{location:"inchannel",name:"Tomoaki Ohi..",volume:"50",url:"img/ohira.jpeg",group:0},
{location:"inchannel",name:"Woosuk Cha..",volume:"50",url:"img/woosuk.jpeg",group:0},
{location:"inchannel",name:"Luca Rigaz..",volume:"50",url:"img/luca.jpeg",group:0},
{location:"inchannel",name:"SooIn Nam",volume:"50",url:"img/sooin.jpeg",group:0}
];
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
I am trying to copy ce_info to inch_info.
It seems like it does not work.It occurs an error when I try to copy ce_info to inch_info
Any thought?
Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.
var foo = ['a','b','c','d','e'];
var bar = foo.slice();
now foo and bar are 5 member arrays of 'a','b','c','d','e'
inchat_count seems to be uninitialized.
var inch_info=[{location:"icha",name:"",volume:"50",url:""}];
var inchat_count = 0; // You forgot this line!!
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
You still have a typeO in your code
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
shouldnt location be inchat instead of ichat? Because that is what you check for in this line
if(ce_info[i].location=="inchat")
Furthermore in ce_info there is no location named inchat so the result of this piece of code will not be executed. But if there where an element in ce_info that has the location inchat this will be the code you need to add the location and name to the inch_info array.
Change your for loop in this:
for(var eElem in ce_info)
{
if(ce_info[eElem].location=="inchannel")
{
var temp = {};
temp.name=ce_info[eElem].name;
temp.url=ce_info[eElem].url;
inch_info.push(temp);
}
}
using jQuery you can achieve it so easily:
See a working demo here
following jQuery code makes sure that you do not have a by reference object of ce_info.
jQuery code:
var inch_info= jQuery.extend(true, {}, ce_info);
alert("inch_info: before changing text: "+inch_info[0].location);
inch_info[0].location = "hello world"
alert("inch_info: after changing text: "+inch_info[0].location);
alert("ce_info: after changing text: "+ce_info[0].location);

Categories