Problem creating array in javascript - javascript

i have a javascript code below.
bgCustom = { 'items':[], 'items_num':3, 'element':'#bg_custom_thumbs', 'next': '#bg_custom_next_thumb', 'prev': '#bg_custom_prev_thumb', 'width':165 };
//populate array
bgCustom.items = [["images/backgrounds/bear-ears_thumb.jpg", "bear-ears.jpg", "Bear-Hair"], ["images/backgrounds/blue-swirls_thumb.jpg", "blue-swirls.jpg", "WaterSmoke"]];
ho do i create bgCustom.items array dynamic. means i want a array list
[['val1_1','val1_2','val1_3'],['val2_1','val2_2','val2_3']]
Can any body help me.

You can add arrays to the end of the array:
bgCustomer.items.push(['val1_1','val1_2','val1_3']);
bgCustomer.items.push(['val2_1','val2_2','val2_3']);
You can also assign arrays at specific indexes. The array will automatically expand if you use an index outside the current size:
bgCustomer.items[0] = ['val1_1','val1_2','val1_3'];
bgCustomer.items[1] = ['val2_1','val2_2','val2_3'];

bgCustom = { 'items':[], 'items_num':3, 'element':'#bg_custom_thumbs', 'next': '#bg_custom_next_thumb', 'prev': '#bg_custom_prev_thumb', 'width':165 };
function PushToItems(a,b,c) {
var ar = [a,b,c];
bgCustom.items.push(ar);
}
PushToItems("images/backgrounds/bear-ears_thumb.jpg", "bear-ears.jpg", "Bear-Hair");
That should work for making it a little more dynamic.

Related

How to add the key of the object to the array in js

I have such objects:
robot {
id
skill
currentWorkPlace
}
warehouse {
aiStaff
currentStatus
boxes
}
I have to write a function that should add the id of a new worker to the aiStaff array, and write a reference to the warehouse object to the job in the currentWorkPlace. But I don't know how not to change the array in the warehouse.('registerRobot' function should not rewrite array 'aiStaff' inside 'warehouse' object) and I don't have to create a new variable
There is my code:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff = [robot.id];
}
I dont know how to not rewrite array 'aiStaff'. Please help me Guys.
It looks like your warehouse.aiStaff is an array. In this case change your function to add the robot ID to the array:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push(robot.id);
}
If I understood correctly you need to 'add' a new robot, but you are having the issue that the entire array gets overridden.
Considering warehouse.aiStaff is an array, if you want to add a new 'worker' you need to push the new item into the array.
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push({
id: robot.id
});
}

Problem with a JSON Object ( deep search )

Hi Guys i have a big Problem, i've been trying to solve it for days.I have an entangled JSON Object ( http://ddragon.leagueoflegends.com/cdn/9.1.1/data/de_DE/runesReforged.json ) and for example this Array with my ID's in it.
0: 8214 1: 8112 2: 8005 3: 8010 4: 8112 5: 8359 6: 8437 7: 9923 8: 8112 9: 8021
And I want the id to be searched for with the help of this array in the json Object. And after a match, the content of "icon" should be returned,
but i dont know how :(
I tried it on so many ways, but i dont have the result that i want. The ID's are among others under the_json_object[0].slots[0].runes[0].id
I read that you could solve it with recursive functions but I tried and did not get the desired result.
Maybe you guys can help me :) i would be very thankful
If I've understood you correctly you could do something roughly as follows:
var ids = [8214,8112,8005,8010,8112,8359,8437,9923,8112,8021];
var results = [];
ids.map(function(id) {
results.push({key: id, icon: ''});
});
Then given your object you could map through it's children as folllows:
the_json_object.map(function(item){
item.slots.map(function(slot){
slot.runes.map(function(rune){
if(ids.indexOf(rune.id) != -1) {
results.map(function(result){
if(result.key == rune.id) result.icon = rune.icon;
});
}
});
});
});
var icons = [];
results.map(function(result){
icons.push(result.icon);
});
logging the icons object would then provide you a string array of icons as follows:
["perk-images/Styles/Domination/Electrocute/Electrocute.png", "perk-images/Styles/Domination/HailOfBlades/HailOfBlades.png", "perk-images/Styles/Inspiration/Kleptomancy/Kleptomancy.png", "perk-images/Styles/Precision/PressTheAttack/PressTheAttack.png", "perk-images/Styles/Precision/FleetFootwork/FleetFootwork.png", "perk-images/Styles/Precision/Conqueror/Conqueror.png", "perk-images/Styles/Resolve/GraspOfTheUndying/GraspOfTheUndying.png", "perk-images/Styles/Sorcery/SummonAery/SummonAery.png"]
Hope this helps.
Matt
I think the suitable way would be to sort data. You can do this by splitting the string.
If you split the string on the basis of White spaces you can get key value pairs.
For example from string *
0:8214 1:8112 2:8005 3:8010 4:8112 5:8359 6:8437 7:9923 8:8112 9:8021
var res = str.split(" ");
if you split with white space it will provide you with key value pairs from which you can form a list of objects and it will be easy for you search from it.
If you want an flat array with the all the needed icons, you could use something like this:
let the_runes = [ 8214, 8112, 8005 /* ... */ ];
let the_icons = [];
for (let first_level_obj of the_json_object) {
for (let slot_obj of first_level_obj.slots) {
for (let rune_obj of slot_obj.runes) {
if (the_runes.includes(rune_obj.id)) {
the_icons.push({
id: rune_obj.id,
icon: rune_obj.icon
});
}
}
}
}
The the_icons-array will hold objects with id and its corresponding icon as its properties.

How to compare a 2-D array and 1-D Array and to Store common Data in Another Array in Java Script

I have 2 Arrays and one is 2 dimensional and another is 1 dimensional. I need to compare both and need to store there common data in another array. I tried the below approach:-
tw.local.listtodisplayNW = new tw.object.listOf.listtodisplayNWBO();
//if(tw.local.SQLResults[0].rows.listLength >
// tw.local.virtualServers.listLength)
var k=0;
for (var i=0;i<tw.local.SQLResults[0].rows.listLength;i++)
{
log.info("Inside SQLResults loop - For RuntimeID: "
+tw.local.SQLResults[0].rows[i].data[3]);
for(var j=0;j<tw.local.virtualServers.listLength;j++)
{
log.info("Inside API loop - For RuntimeID: "
+tw.local.virtualServers[j].runtimeid);
if(tw.local.SQLResults[0].rows[i].data[3] ==
tw.local.virtualServers[j].runtimeid)
{
tw.local.listtodisplayNW[k] = new tw.object.listtodisplayNWBO();
tw.local.listtodisplayNW[k].vsysName =
tw.local.virtualServers[j].virtualSystemName;
tw.local.listtodisplayNW[k].vsysID =
tw.local.virtualServers[j].virtualSystemId;
tw.local.listtodisplayNW[k].serverName =
tw.local.virtualServers[j].serverName;
tw.local.listtodisplayNW[k].serverID =
tw.local.virtualServers[j].serverId;
tw.local.listtodisplayNW[k].runtimeID =
tw.local.virtualServers[j].runtimeid;
//tw.local.listtodisplayNW[k].IPAddress =
tw.local.virtualServers[j].nics[j].ipAddress;
log.info("VsysName:
"+tw.local.listtodisplayNW[k].vsysName+"RuntimeID:
"+tw.local.listtodisplayNW[k].runtimeID);
//tw.local.listtodisplayNW[k] = new
tw.object.listtodisplayNWBO();
tw.local.listtodisplayNW[k].currentSpeed =
tw.local.SQLResults[0].rows[i].data[5];
log.info("VsysName:
"+tw.local.listtodisplayNW[k].vsysName+"RuntimeID:
"+tw.local.listtodisplayNW[k].runtimeID+"CurrentSpeed:
"+tw.local.listtodisplayNW[k].currentSpeed);
if(tw.local.listtodisplayNW[k].currentSpeed != "100 Mbps")
{
tw.local.listtodisplayNW[k].desiredSpeed = "100 Mbps";
}
else
{
tw.local.listtodisplayNW[k].desiredSpeed = "1 Gbps";
}
log.info("DesiredSpeed:
"+tw.local.listtodisplayNW[k].desiredSpeed);
k++;
}
}
log.info("Length of
listtodisplayNW"+tw.local.listtodisplayNW.listLength);
}
In above code SQLResults is a 2-d array and virtualServers is a 1-D array.
I need to compare both these array and common data need to be store in another array. Here performance is not good. Is there any other way to do this efficiently. Please make a needful favour and Thanks in advance.
Assuming integer data, the following example works on the theme of array implementation of set intersection, which will take care of performance.
Convert 2D array to 1D.
var 2DtoIDArray = 2DArray.join().split(",");
Create an array named marker whose purpose is to serve as a lookup that element.
This needs to be done as follows.
Iterate through the smaller array, say 1DArray and keep setting marker as follows throughout iteration.
marker[1DArray[counter]]='S1';
Now iterate through 2Dto1DArray array(you may use nested loop iteration if you dont want to convert it to 1 dimesnional) and for each element
of this array check if its marked as 'S1' in the marker lookup array.
If yes, keep adding the elements in the commonElementsArray.
Follow this simple approach
Since the matching condition is only one between the two large arrays, create two maps (one for each array) to map each record against that attribute which is to be matched
For SQLResults
var map1 = {};
tw.local.SQLResults[0].rows.each( function(row){
map1[ row.data[3] ] = row;
});
and similarly for virtual servers
var map2 = {};
tw.local.virtualServers.each( function(vs){
map2[ vs.runtimeid ] = vs;
});
Now iterate these two maps wrt to their keys and set the values in new array
new array being tw.local.listtodisplayNW
tw.local.listtodisplayNW = [];
Object.keys( map1 ).forEach( function( key ){
if( map2[ key ] )
{
//set the values in tw.local.listtodisplayNW
}
})
Complexity of the approach is simply O(n) since there is no nested loops.

How to push object to array in angularjs?

This is my code
$scope.studentDetails=[];
$scope.studentIds={};
$scope.studentIds[0]{"id":"101"}
$scope.studentIds[1]{"id":"102"}
$scope.studentIds[2]{"id":"103"}
in the above code when i select student id:101 i got marks from services like
$scope.studentMarks={};
$scope.studentMarks[0]{"marks":"67"}
$scope.studentMarks[1]{"marks":"34"}
next i select student id:102 i got marks from services like
$scope.studentMarks={};
$scope.studentMarks[0]{"marks":"98"}
$scope.studentMarks[1]{"marks":"85"}
finally i want to store student details in to one array like
$scope.studentDetails=[{"id":"101","marks":[67,34]},{"id":"102","marks":[98,85]}]
using angularjs.
Seems like its more of a JS question than angular.
What about the Javascript push method?
$scope.studentDetails.push({id: 101, marks: [67, 34]});
You can use Array.push to add one object, or concat, to concat array into another array. See the references.
angularJS is just a library to extend Javascript. You push into an array just like you would any object in Javascript.
First off, you need to declare an array.
$scope.studentIds = []; // Array of student ids.
Then when you want to add, you push:
$scope.studentIds.push({id: "101"});
To do this naively you need to loop through the student ids and then loop through the marks object and adding it to your studentDetails object if the ids match:
var studentDetails = [];
for (var id in studentIds) {
var studentDetail = {}; // this will be a single student
var marks = [];
if (studentIds.hasOwnProperty(id)) {
for (var mark in studentMarks) {
if (studentMarks.hasOwnProperty(mark) && mark.id === id) {
studentDetail.id = id;
marks.push(mark.marks);
}
}
studentDetail.marks = marks;
}
studentDetails.push(studentDetail);
}
$scope.studentDetails = studentDetails;

Create an array of specific elements from another array?

I have an array that can't be changed in terms of the element positions:
var array = ['item1', 'section1', 'section2', 'section3', 'section4', 'section5', 'prod1', 'prod2']
I want to make a new array from 'array' that takes the elements from position 1 - 5 (so all the section elements). It needs to be by position as the section elements make change by name.
var array2=array.slice(1,6)
See here for more information.
let's say we have an array like this
const FILES_WITH_10_ASSETS = [
'../assets/uploads/Desktop-300x600.jpeg',
'../assets/uploads/Desktop-728x90.png',
'../assets/uploads/Mobile-160x600.jpeg',
'../assets/uploads/Mobile-300X50.jpeg',
'../assets/uploads/Mobile-320x50.jpeg',
'../assets/uploads/Mobile-320x480.jpeg',
'../assets/uploads/Mobile-1024x768.jpeg',
'../assets/uploads/Tablet-300x250.jpeg',
'../assets/uploads/Tablet-Interstitial-320x480.gif',
'../assets/uploads/Tablet-Interstitial-320x480.jpeg'
];
now we want some specific items from an array, we will create a function for this, here I have stored the function in an constant for further use
const SELECT_ASSETS = function(assetName: string) {
let filtered_assets: string[] = [];
for (let i in FILES_WITH_10_ASSETS) {
if (FILES_WITH_10_ASSETS[i].includes(assetName) === true) {
filtered_assets.push(FILES_WITH_10_ASSETS[i]);
}
}
return filtered_assets;
};
and we call the method like this in our file
const ASSETS_NAME = SELECT_ASSETS(ASSET_NAME);
now we can pass the assets name to any function or method, if we pass the ASSET_NAME as Tablet we will get all three tablet paths, or if we change it to Mobile, we will get all five Mobile paths

Categories

Resources