Create stacked array with javascript - javascript

I have an original two-dimensional array which represents the 100% version budget per year, looking like:
budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]]
Now I need to create subarrays of the budget for projects. For example:
project1 = [['2001-01-01', 10], ['2001-01-02', 11]]
meaning, that it goes for 2 days and uses 10% of the available budget.
I create the project arrays by the following function:
project1 = [[]];
project1 = new_project(budget, 0, 1, 0.1);
function new_project(origin, start, end, factor) {
var result = [[]];
result = origin.slice(parseInt(start), parseInt(end)).map(function (item) {
return [item[0], parseInt(item[1]) * factor]
});
return result;
}
Problem
How can I decrease my budget array now by the values of my created project?
I need to modifiy budget on the fly by calling new_project in order to get:
budget = [['2001-01-01', 90], ['2001-01-02', 99],..., ['2001-12-31', 140]]
jsfiddle of the setup
http://jsfiddle.net/gcollect/7DAsL/

You can use the built-in array forEach() method to loop over the subset of the budget (ie project1) and change the original budget's values. I've made a function called decreaseBudget() which will do that for you:
function decreaseBudget(original, subset) {
// Loop over the subset's items.
subset.forEach(function(item, index){
// Get the original amount out of the original item.
// As we are looping over subset it will always have less items then the original
// so no need to check if the index is valid.
var originalItemAmount = original[index][1];
// Decrease the amount and set it back in it's original place
original[index][1] = (originalItemAmount - item[1]);
});
};
Call it with the budget and the project1 arrays as arguments to change the value of the budget array. Take a look at the updated fiddle:
http://jsfiddle.net/7DAsL/4/
If you prefer decreaseBudget() won't change the original array but return a copy you could use the array .slice() method to make a shallow copy of the original, make the changes to the copy and return it.

I got the answer. see http://jsfiddle.net/gcollect/7DAsL/2/
solution
function new_project(origin, start, end, factor) {
var result = [
[]
];
result = origin.map(function (item) {
return [item[0], (item[1] * factor)]
});
for (var i = 0; i < result.length; i++) {
origin[i][1] = parseInt(origin[i][1]) - parseInt(result[i][1]);
}
result = origin.slice(parseInt(start), parseInt(end));
return result;
};

Related

Get "leaderboard" of list of numbers

I am trying to get a kind of "leaderboard" from a list of numbers. I was thinking of making an array with all the numbers like this
var array = [];
for (a = 0; a < Object.keys(wallets.data).length; a++) { //var wallets = a JSON (parsed) response code from an API.
if (wallets.data[a].balance.amount > 0) {
array.push(wallets.data[a].balance.amount)
}
}
//Add some magic code here that sorts the array into descending numbers
This is a great option, however I need some other values to come with the numbers (one string). That's why I figured JSON would be a better option than an array.
I just have no idea how I would implement this.
I would like to get a json like this:
[
[
"ETH":
{
"balance":315
}
],
[
"BTC":
{
"balance":654
}
],
[
"LTC":
{
"balance":20
}
]
]
And then afterwards being able to call them sorted descending by balance something like this:
var jsonarray[0].balance = Highest number (654)
var jsonarray[1].balance = Second highest number (315)
var jsonarray[2].balance = Third highest number (20)
If any of you could help me out or point me in the right direction I would appreciate it greatly.
PS: I need this to happen in RAW JS without any html or libraries.
You should sort the objects before making them a JSON. You can write your own function or use a lambda. See this [https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value]
Since you are dealing with cryptocurrency you can use the currency-code as a unique identifier.
Instead of an array, you can define an object with the currency as properties like this:
const coins = {
ETH: [300, 200, 500],
BTC: [20000, 15000, 17000]
}
then you can access each one and use Math.max or Math.min to grab the highest / lowest value of that hashmap. E.G. Math.max(coins.BTC)
And if you need to iterate over the coins you have Object.keys:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Thank you all for your answer. I ended up using something like:
leaderboard = []
for (a = 0; a < Object.keys(wallets.data).length; a++) {
if (wallets.data[a].balance.amount > 0) {
leaderboard.push({"currency":wallets.data[a].balance.currency, "price":accprice}) //accprice = variable which contains the value of the userhold coins of the current coin in EUR
}
}
console.log(leaderboard.sort(sort_by('price', true, parseInt)));

Generate combination of products given a total price limit

I have an array of products id, and 2 arrays with product id in key and price and unique flag in values.
I would like to have all unique combinations of products under a given total limit price :
a product could be several times in combination, except if it is flagged as unique
combination should be sorted by product id
a valid combination is one to the which we can't add product
Sample:
products = [1, 2, 3];
productPrices = {1:10, 2:15, 3:10};
productUnique = {1:true, 2:false, 3:false};
limitPrice = 40;
expected result = [[1,2,2],[1,2,3],[1,3,3,3],[2,2,3],[2,3,3],[3,3,3,3]];
How can I obtain this result in javascript if possible ?
Thanks for the help.
I would suggest another format for your input, so it is a single array of objects, where each of those objects has an id, price and unique property.
Then with that array of objects and the limit price, use recursion to select at each level of recursion a product to be added to a series of products until none can be added. At that time add the selected product list to a results array.
When selecting a product, determine which products can still be selected in the next level of recursion: when a unique product was selected, then don't pass that on as a selection possibility to the next level.
To avoid duplicates, once a product is no longer selected from, don't come back to it at deeper recursion levels; so pass on a shorter product list in recursion when it is decided not to pick the same product again. The recursion ends when the cheapest, still available product is more expensive than the amount that is still available.
Here is a snippet:
function intoOne(products, productPrices, productUnique) {
return products.map( (id) => ({
id,
price: productPrices[id],
unique: productUnique[id]
}));
}
function combinations(products, limitPrice) {
const results = [];
function recurse(sel, products, minPrice, maxPrice) {
products = products.filter(p => p.price <= maxPrice);
if (!products.length && minPrice > maxPrice) return results.push(sel);
products.forEach( (p, i) => {
recurse(sel.concat(p.id), products.slice(i+p.unique),
minPrice, maxPrice-p.price);
minPrice = Math.min(minPrice, p.price);
});
}
recurse([], products, limitPrice, limitPrice);
return results;
}
var products = [1, 2, 3],
productPrices = {1:10, 2:15, 3:10},
productUnique = {1:true, 2:false, 3:false},
limitPrice = 40;
// Combine product characteristics in more suitable structure
products = intoOne(products, productPrices, productUnique);
// Call main algorithm
var result = combinations(products, limitPrice);
console.log(JSON.stringify(result));
You could take an iterative and recursive approach by checking the sum, length and unique parameter for next call of the same function with changed index or temporary items.
If the sum is smaller than the limit, the temporary result is added to the result set.
function iter(index, temp) {
var product = products[index],
sum = temp.reduce((s, k) => s + prices[k], 0);
if (sum + prices[product] > limit) {
result.push(temp);
return;
}
if (!unique[product] || temp[temp.length - 1] !== product) {
iter(index, temp.concat(product));
}
if (index + 1 < products.length) {
iter(index + 1, temp);
}
}
var products = [1, 2, 3],
prices = { 1: 10, 2: 15, 3: 10 },
unique = { 1: true, 2: false, 3: false },
limit = 40,
result = [];
iter(0, []);
console.log(JSON.stringify(result));

How to find the position of all array items from a loop

I'm brand new to programming so I apologize if this is a simple question.
I had a unique practice problem that I'm not quite sure how to solve:
I'm dealing with two arrays, both arrays are pulled from HTML elements on the page, one array is representing a bunch of states, and the next array is representing their populations. The point of the problem is to print the name of the states and their less than average populations.
To find and print all of the populations that are less than the average I used this code:
function code6() {
// clears screen.
clr();
// both variables pull data from HTML elements with functions.
var pop = getData2();
var states = getData();
var sum = 0;
for( var i = 0; i < pop.length; i++ ){
sum += parseInt( pop[i], 10 );
var avg = sum/pop.length;
if (pop[i] < avg) {
println(pop[i]);
// other functions used in the code to get data, print, and clear the screen.
function getData() {
var dataSource = getElement("states");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Get the data from second data column
function getData2() {
var dataSource = getElement("pops");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Clear the 'output' text area
function clr() {
var out = getElement("output");
out.value = "";
}
// Print to the 'output' HTML element and ADDS the line break
function println(x) {
if (arguments.length === 0) x = '';
print(x + '\n');
}
Now I just need to know how to get the value of these positions within the array so I can pull out the same positions from my states array and display them both side by side. Both arrays have the identical amount of items.
I hope this makes sense and thanks in advance to anyone who has time to take a look at this.
Best regards,
-E
Its a little hard to tell what you are trying to accomplish, but I guess you are going for something like:
'use strict'
function code6() {
const populations = ['39000000', '28000000', '21000000'];
const stateNames = ['california', 'texas', 'florida'];
const states = populations.map((population, i) => ({
'name': stateNames[i],
'population': Number(population),
}));
const sum = states.reduce((sum, state) => sum + state.population, 0);
const average = sum / populations.length;
states
.filter(state => state.population < average)
.forEach(state => {
const name = state.name;
const population = state.population;
console.log(`state name: ${name}, population: ${population}`);
});
}
// run the code
code6();
// state name: texas, population: 28000000
// state name: florida, population: 21000000
I took the liberty of refactoring your code to be a little more modern (es6) and Idiomatic. I hope its not to confusing for you. Feel free to ask any questions about it.
In short you should use:
'use strict' at the top of your files
const/let
use map/filter/forEach/reduce to iterate lists.
use meaningfull names
, and you should avoid:
classic indexed for-loop
parseInt
, and pretty much never ever use:
var
If your states array is built with corresponding indices to your pop one, like this:
states; //=> ['Alabama', 'Alaska', 'Arizona', ...]
pop; //=> [4863300, 741894, 6931071, ...]
then you could simply update your print statement to take that into account:
if (pop[i] < avg) {
println(state[i] + ': ' + pop[i]);
}
Or some such.
However, working with shared indices can be a very fragile way to use data. Could you rethink your getData and getData2 functions and combine them into one that returns a structure more like this the following?
states; //=> [
// {name: 'Alabama', pop: 4863300}
// {name: 'Alaska', pop: 741894},
// {name: 'Arizona', pop: 6931071},
// ...]
This would entail changes to the code above to work with the pop property of these objects, but it's probably more robust.
If your pop and state looks like:
var state = ['state1', 'state2', ...];
var pop = ['state1 pop', 'state2 pop', ...];
Then first of all, avg is already wrong. sum's value is running along with the loop turning avg's formula into sum as of iteration / array length instead of sum of all pops / array length. You should calculate the average beforehand. array.reduce will be your friend.
var average = pop.reduce(function(sum, val){return sum + val;}, 0) / pop.length;
Now for your filter operation, you can:
Zip up both arrays to one array using array.map.
Filter the resulting array with array.filter.
Finally, loop through the resulting array using array.forEach
Here's sample code:
var states = ['Alabama', 'Alaska'];
var pop = [4863300, 741894];
var average = pop.reduce(function(sum, val){return sum + val;}) / pop.length;
console.log('Average: ' + average);
states.map(function(state, index) {
// Convert 2 arrays to an array of objects representing state info
return { name: state, population: pop[index] };
}).filter(function(stateInfo) {
console.log(stateInfo);
// Filter each item by returning true on items you want to include
return stateInfo.population < average;
}).forEach(function(stateInfo) {
// Lastly, loop through your results
console.log(stateInfo.name + ' has ' + stateInfo.population + ' people');
});

Group by in javascript or angularjs

I just want to do sum value column based on the Year and my data is below, but I don't know how to do this either using angular(in script) or javascript.
[
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
]
I want to perform the sum on Value column and remove Product column as well.
Thanks
Edit As commenters have pointed out, this doesn't even require Lodash. Been using Lodash so much for current project I forgot reduce is built in. :-)
Also updated to put data in desired form [{"yyyy" : xxxx},...].
This code will accomplish this:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
var sum = data.reduce(function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
result = [];
for(year in sum){
var tmp = {};
tmp[year] = sum[year];
result.push(tmp);
}
console.log(result);
RESULT:
[{"2013" : 70}, {"2014" : 78}, {"2015" : 125}, {"2016" : 153}]
ORIGINAL ANSWER
The easiest way I can think of to do this is with the Lodash Library. It gives you some nice functional programming abilities like reduce, which basically applies a function to each element of an array or collection one by one and accumulates the result.
In this case, if you use Lodash, you can accomplish this as follows:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
result = _.reduce(data, function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
This yields:
{
"2013": 70,
"2014": 78,
"2015": 125,
"2016": 153
}
Basically, what we're telling Lodash is that we want to go through all the elements in data one by one, performing some operation on each of them. We're going to save the results of this operation in a variable called res. Initially, res is just an empty object because we haven't done anything. As Lodash looks at each element, it checks if that Product's year is in res. If it is, we just add the Value to that year in res. If it's not, we set that Year in res to the Value of the current product. This way we add up all the product values for each year.
If you want to try it out you can do it here:
Online Lodash Tester
Cheers!
You could do this using plain JavaScript. We use an object that will hold the results and the forEach array method. The object that would hold the results would have as keys the years and as values the sums of the corresponding values.
var data = [
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
];
groupedData = {};
data.forEach(function(item){
var year = item.Year;
var value = item.Value;
if(groupedData.hasOwnProperty(year)){
groupedData[year]+=value;
}else{
groupedData[year]=value;
}
});
console.log(groupedData);

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.

Categories

Resources