Javascript - Push to a new array dynamically? - javascript

Hello I am new to javascript so I'm sorry in advance if my explanation is not the best.
I am getting my data back from an array called myData. I have a condition statement which checks the page url and depending on the url I am pushing a specific index of an array to a new array called stateArray
At the moment I am using the push method like this:
stateArray.push(myData[1][5], myData[2][5], myData[3][5], myData[4][5], myData[5][5], myData[6][5], myData[7][5], myData[8][5], myData[9][5], myData[10][5], myData[11][5], myData[12][5], myData[13][5], myData[14][5], myData[15][5], myData[16][5], myData[17][5], myData][5])
the return of stateArray is giving back the data I am expecting but I am going to have ten different conditions and would like to know if there is a way of doing the push 17 times for every condition better?
Every element is the same for the condition. For example
if (url.includes('/states/') {
stateArray.push(myData[1][5], myData[2][5], myData[3][5], myData[4][5], myData[5][5], myData[6][5], myData[7][5], myData[8][5], myData[9][5], myData[10][5], myData[11][5], myData[12][5], myData[13][5], myData[14][5], myData[15][5], myData[16][5], myData[17][5], myData][5])
} else if (url.includes('/homes/) {
stateArray.push(myData[1][6], myData[2][6], myData[3][6], myData[4][6], myData[5][6], myData[6][6], myData[7][6], myData[8][6], myData[9][6], myData[10][6], myData[11][6], myData[12][6], myData[13][6], myData[14][6], myData[15][6], myData[16][6], myData[17][6], myData][6])
} else if (url.incldues('/retail/) {
stateArray.push(myData[1][7], myData[2][7], myData[3][7], myData[4][7], myData[5][7], myData[6][7], myData[7][7], myData[8][7], myData[9][7], myData[10][7], myData[11][7], myData[12][7], myData[13][7], myData[14][7], myData[15][7], myData[16][7], myData[17][5], myData][7])
}
Like I mentioned earlier I currently have 10 conditions and it is very difficult to maintain and update. Is there a way of generating the same results dynamically? I believe this can be done through a loop but I am not familiar with the syntax in regards to pushing at a specific index and ending at a specific index.
My expected outcome is a short handed way of going through each condition and pushing into the new Array.

You can use forEach:
if (url.includes('/states/')) {
myData.forEach(e => stateArray.push(e[5]));
} else if (url.includes('/homes/')) {
myData.forEach(e => stateArray.push(e[6]));
} else if (url.includes('/retail/')) {
myData.forEach(e => stateArray.push(e[7]));
}
(Also note you need a second ) at the end of your if to close off both the if and the includes)

Related

Update a rather large if statement of values to be an array

Here is a piece of JavaScript code that is rather large and clunky. I would like to take all of the setValue() code values and place it all into an array. At this point it seems as though I should just be able to take the values and place them into an array but I feel like I am skipping a step. Thanks for your help.
if (VS_group == "group") {
setValue('CORNER_1A_COUNT',"S06");
setValue('INBOARD_111_COUNT',"S06");
setValue('INBOARD_112_COUNT',"S06");
setValue('INBOARD_113_COUNT',"S06");
setValue('INBOARD_114_COUNT',"S06");
setValue('INBOARD_115_COUNT',"S06");
setValue('INBOARD_116_COUNT',"S06");
setValue('INBOARD_117_COUNT',"S06");
setValue('INBOARD_118_COUNT',"S06");
setValue('INBOARD_119_COUNT',"S06");
setValue('INBOARD_120_COUNT',"S06");
setValue('CORNER_1C_COUNT',"S06");
setValue('CORNER_1A',"RED");
setValue('INBOARD_111',"RED");
setValue('INBOARD_112',"RED");
setValue('INBOARD_113',"RED");
setValue('INBOARD_114',"RED");
setValue('INBOARD_115',"WHT");
setValue('INBOARD_116',"WHT");
setValue('INBOARD_117',"BLU");
setValue('INBOARD_118',"BLU");
setValue('INBOARD_119',"BLU");
setValue('INBOARD_120',"BLU");
setValue('CORNER_1C',"BLU");
setValue('ALLEY_1D_COUNT',"S06"); setValue('ALLEY_1P_COUNT',"S06");
setValue('ALLEY_1D',"WHT"); setValue('ALLEY_1P',"WHT");
setValue('CORNER_1B_COUNT',"S06");
setValue('INBOARD_131_COUNT',"S06");
setValue('INBOARD_132_COUNT',"S06");
setValue('INBOARD_133_COUNT',"S06");
setValue('INBOARD_134_COUNT',"S06");
setValue('INBOARD_135_COUNT',"S06");
setValue('INBOARD_136_COUNT',"S06");
setValue('INBOARD_137_COUNT',"S06");
setValue('INBOARD_138_COUNT',"S06");
setValue('INBOARD_139_COUNT',"S06");
setValue('INBOARD_140_COUNT',"S06");
setValue('CORNER_1D_COUNT',"S06");
setValue('CORNER_1B',"RED");
setValue('INBOARD_131',"RED");
setValue('INBOARD_132',"RED");
setValue('INBOARD_133',"RED");
setValue('INBOARD_134',"RED");
setValue('INBOARD_135',"RED");
setValue('INBOARD_136',"BLU");
setValue('INBOARD_137',"BLU");
setValue('INBOARD_138',"BLU");
setValue('INBOARD_139',"BLU");
setValue('INBOARD_140',"BLU");
setValue('CORNER_1D',"BLU");
}
You can store these values in an array and apply a loop on that array something like that
[ ['INBOARD_140_COUNT', 'S06'], ['INBOARD_141_COUNT', 'S07'] ].forEach(([key, value] => setValue(key, value));
When you run code snippet on StackOverflow it will give an error because "setValue()" is not defined, I wrote this just for better understanding

Filter an Array of Objects from an Array in TypeScript

I built a custom component that filters an array of objects. The filter uses buttons, sets from active to non-active and allows more than one option on/off at the same time.
StackBlitz of my attempt - https://stackblitz.com/edit/timeline-angular-7-ut6fxu
In my demo you will see 3 buttons/options of north, south and east. By clicking on one you make it active and the result should include or exclude a matching "location" either north, south and east.
I have created my methods and structure to do the filtering, I'm struggling with the final piece of logic.
So far I have created a method to create an array of filtered locations depending on what the user clicks from the 3 buttons.
Next this passes to my "filter array" that gets the logic that should compare this filtered array against the original to bring back the array of results that are still remaining.
Its not quite working and not sure why - I originally got this piece of functionality working by using a pipe, but fore reasons do not want to go in that direction.
//the action
toggle(location) {
let indexLocation = this.filteredLocations.indexOf(location);
if (indexLocation >= 0) {
this.filteredLocations = this.filteredLocations.filter(
i => i !== location
);
} else {
this.filteredLocations.push({ location });
}
this.filterTimeLine();
}
// the filter
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
//the logic
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
https://stackblitz.com/edit/timeline-angular-7-ut6fxu
Sorry for my expression but u have a disaster in your code. jajaja!. maybe u lost that what u need but the logic in your functions in so wrong. comparing string with objects. filter a array that filter the same array inside... soo u need make a few changes.
One:
this.filteredLocations.push({location});
Your are pushing object. u need push only the string.
this.filteredLocations.push(location);
Two:
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
in this function you filter the timeLine array. and inside of contactMethodFilter you call filter method to timeLine again....
See a functional solution:
https://stackblitz.com/edit/timeline-angular-7-rg7k3j
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
This function is not returning any value and is passed to the .filter
Consider returning a boolean based on your logic. Currently the filter gets undefined(falsy) and everything would be filtered out

checking an object property when adding to Array - ES6

I have a simple algorithm problem but couldn't find a proper solution. There is an array and I just want to add an item in the array if the property of recipe_id is not the same in any objects recipe_id property value in the Array.
I want to prevent any item to add if it has the same property value. If the value of the property is different then it is ok. Thus all the objects in the Recipes array should have different recipe_id values. I write these code but it seems it's not working correctly
here is JSBin link : link
const Recipes =[
{recipe_id:4},
{recipe_id:5}
]
onClickedHandler = (recipe_id) => {
const favData = {
recipe_id: recipe_id,
}
if (Recipes.length > 0) {
for (let item in Recipes) {
if (Recipes[item].recipe_id !== recipe_id) {
console.log("added in the loop!")
Recipes.push(item)
} else {
console.log("it is already in the Recipe list!")
}
}
} else {
console.log("Recipes is empty")
Recipes.push({recipe_id:recipe_id})
}
}
onClickedHandler(9)
console.log(Recipes.length)
Use the Array.some method to check if the ID exists in the array.
You probably need something like:
const Recipes =[
{recipe_id:4},
{recipe_id:5}
];
function addRecipe(recipeId) {
if(!Recipes.some(item => item.recipe_id === recipeId)) {
Recipes.push({recipe_id:recipeId});
console.log("Not duplicate, inserted");
} else {
console.log("duplicate");
}
}
addRecipe(4);
addRecipe(6);
console.log(Recipes)
The problem is that you're going through elements, and first item when you're adding an element with id of 4 there is one item with that ID.
It doesn't pass, next iteration, it checks agains the element with different ID. It passes and goes to ID.
You need a loop within a loop, for example try .filter function, if it returns undefined, you can add it, otherwise don't add.
Well you are pushing an object with new recipe whenever you find another object with a different id instead of checking all of them before adding.
if you were to try adding another object with id 7 (onClickedHandler(7)) after all of your code you would end up with 3 different objects with id 7
This happens because you are not returning in your for loop. Of course, it will iterate over all items and, for each item that has different recipe_id, it will append a new item. You should jump out your function once you find the recipe is already there:
for (let item in Recipes) { // Iterate over each item (no need to test length)
if (Recipes[item].recipe_id !== recipe_id) { // Break if recipe already there.
console.log("it is already in the Recipe list!");
return;
}
}
// Otherwise, it is safe to append the recipe_id:
Recipes.push({recipe_id:recipe_id});
console.log("added in the loop!");
Now, when you find the same recipe_id, you exit from your function.

removing objects in an object in an array javascript

I've done some research on this issue. I am trying to manipulate an array of calculated values that looks like this in the console:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:Complex {re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
8:Complex { re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
This array is created dynamically through some math that I've come up with so there is no input data that I can give you. I'm trying to make the above array look like this:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:40.38334500994142
8:39.55961661806138
Using mathjs, I was able to evaluate my expressions and dynamically add the values into an array with the array.push command and display them. However, my code breaks once the imaginary values pop up in the results of my array.
How can I remove these imaginary numbers from my array? In other words, I need to remove the "im:" parts of the values when they begin to appear before I push them to the displayed array.
I tried to do this with some code I found from a previous answer to someone else's question (How do I remove a particular element from an array in JavaScript?) splice command like this:
var nodeVoltage2 = parser.eval(expression2);
//checks if there are imaginary values and removes them
if ("im" in nodeVoltage2) {
nodeVoltage2.splice(2,1)
}
//adds value to result array for analysis
nodeVoltages.push(nodeVoltage2);
but it returns in the console that "im is not defined".
Any help is greatly appreciated!
You can use the array map function.
Basically, we loop through the array. If the item has a .re property, we take that value only. If there is no .re property, we keep the value as is.
We can either write that in shorthand, as with result using the ternary operator and arrow function, or we can write it in a slightly more verbose but traditional way, as with resultTwo
let data = [
48
,47.71306060387108
,47.250273223993105
,46.59686907269243
,45.71876416434013
,44.53304242029258
,42.745236969423615
,{re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
,{ re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
]
let result = data.map((x) => x && x.re ? x.re : x);
let resultTwo = data.map(function(elem) {
// First, we need to check that the array element is not null / undefined
// We then need to check that it has a property called re that is also not null / undefined
if (elem != null && elem.re != null) {
// Just return the property we're interested in
return elem.re;
} else {
// Return the element as is
return elem;
}
});
console.log(result);
console.log(resultTwo);

can't get nested forEach to work in Javascript

So I guess the title is selfexplanatory. I have some code with nested forEach loops inside it. The loops are iterating over an array of chapter objects. Each object can have multiple child nodes and they again can have multiple child nodes, and so on.
I want to end up with one array which contains nested arrays with the child nodes.
So far my code looks like this:
exports.chapter = function(req, res) {
var chapters = [],
result = [];
chapters = exports.index(req, res);
chapters.forEach(function(chapter) {
if(chapter.orphan){
result.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
function getChildren(siblings) {
var children = [];
chapters.forEach(function(chapter) {
if($.inArray(chapter, siblings)){
children.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
return children;
};
};
I don't get any errors except for my page not loading. It doesn't write anything in my console. I think it's a problem in the setup but I'm unable to find out where at the moment. Really hope you guys can help.
Most likely problem is here:
if($.inArray(chapter, siblings)){
$.inArray is a horribly misnamed method: It returns an index, or -1 if not found, not a flag as the name implies. -1 is, of course, truthy; and 0 (a valid index), is falsey, so your if probably wants to be
if($.inArray(chapter, siblings) != -1){
// We found it...
}
or possibly
if($.inArray(chapter, siblings) == -1){
// We didn't find it
}
It's a bit strange.. I don't understand why you're using 'add' instead of 'push' method. If I try to "add" an object to an array I get an usual error. Don't you?

Categories