how to get the sum of data numbers inside an array - javascript

I am currently studying Vue and creating a personal account for the gazoline company.
I have an API IMG in console log
inside the data array there is also a transfer array, also u can see in below picture.
This data is output like this :
I want to get the amount of income in each tankfarme. How can I do it ?
somehow I was able to get the amount of the expense, but it receives the entire amount, and not in one tankfarm. Here is code
const getSumExpense = computed(() => {
let array = getTransfers.value.transfers.data;
let sum = 0;
array.forEach((element) => {
let arrayIncome = element.transfer;
arrayIncome.forEach((el) => {
sum = sum + el.expense;
});
});
return sum;
});
please help me, if you do not understand what I wrote, also tell me, I will try to write better

You can Array.prototype.reduce()
Code:
const arrayIncome = [{expense: 20}, {expense: 30}, {expense: 40}]
const sum = arrayIncome.reduce((a, { expense: e }) => a + e, 0)
console.log(sum)

If you want to get the sum of some specific tankfarm then you have to filter the array first and then with the help of reduce you can sum the records.
const data= [{tankfarm: 'cymma', transfer: [{expense: 10}, {expense: 20}]}]
const result = data.filter(element => element.tankfarm === 'cymma')[0].transfer.reduce((a, { expense: e }) => a + e, 0)
console.log("cymma expense", result)

Related

Get max top 10 element in array in javascript

I have an array something like that and I want to sort by population property.
const countries = [
{"name":"Burkina Faso",population:19034397},
{"name":"Burundi",population:10114505}
...
]
Then I want to get top max 10 object with name and property into something like that
const data = {
labels=[<country names>]
datasets:[
{data:[<population numbers>]}
]
}
I tried some code
const sortItem = () => {
let arr =[]
let values = dataSource.map(item => arr.push({name:item.name,population:item.population}))
let topValues = values.sort((a,b) => b.population-a.population);
console.log(topValues) // output 1,2,3,4,5...
}
But I can't get what I want. How can I achieve the solution ?

Get cypress database query output objects in to variables

I have a cypress test which has been set up with mysql node module. When I run bellow mentioned test Its giving output as follows.
const executeQuery = (query) => {
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
cy.log(rec)
})
}
Query:
select *
from Users
where email = 'sheeranlymited#lymitedtest.com'
OUTPUT: log [Object{23}]
Query:
select firstname
from Users
where email = 'sheeranlymited#lymitedtest.com'
OUTPUT: log [{firstname: Edward}]
instead of cy.log(rec) I want to get the output of 23 columns to assign in to different variables based on the column name.
Appreciate if someone can help me to resolve this...
You can use Object.values in js to retrieve values from your object
Let's say you need to extract the value of the 3rd column, so your code will look like,
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
const results = Object.values(rec[0])
// results[index of the column] will output the results
cy.log(results[3])
})
We can do a small modification to make your task easier,
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
const Values = Object.values(rec[0]);
const keys = Object.keys(rec[0]);
let result = {};
let index = 0;
keys.forEach(key => {
result[keys[index]] = Values[index];
i++
})
//result.firstName will give you your results
cy.log(result.firstName);
})
In this way, we are generating key-value pairs having the key as the column name. So you can use the column name to find the value.
Hope this helps.
cheers.

How to use brainjs to find phone numbers in text - without regex

I'm playing with BrainJS and looks awesome! However, I just came across a problem: how do I train my Neural Network to learn a general idea of how a phone number looks like (I guess feeding in a long list of phone numbers?) and after that, how do I actually run BrainJS to go through some text and find a phone number in it?
If I manage to do this I guess I can teach the NN to learn to find other meaningful information, all of this without using Regex!
I've checked all available features and I can't find what I need: Find a piece of specific data from the input based on what the neural network has been trained with.
Here a piece of code that I believe might be close to what I need, it understands there is a phone number(s) in the sentence based on training. What I want to achieve is get the phone number in the output, potentially on a piece of text it has never seen before.
var brain = require('brainjs');
const learnPhoneData = [
{
input: "Our phone number is 06545 294064 or 29495 195869",
output: {phone_number: 1}
},
{
input: "Our direct line is 36496 496743",
output: {phone_number: 1}
},
{
input: "Give us a call on our 02453 753425.",
output: {phone_number: 1}
}
// ... more of the above
]
const nonPhoneData = [
{
input: "Opening hours Monday to Friday - 9:00am to 5.00pm.",
output: {non_phone_number: 1}
},
{
input: "If you need help with your TV or radio broadcast licence please contact email#site.co.uk.",
output: {non_phone_number: 1}
},
{
input: "Welcome to our website!",
output: {non_phone_number: 1}
}
// ... more of the above
]
// of course the larger the datasets, the more accurate the AI.
var maxLengthInput = -1;
const normalizeArray = arr => {
while (arr.length < maxLengthInput) {
arr.push(0);
}
return arr;
}
const fixLengths = (data) => {
for (let i = 0; i < data.length; i++) {
if (data[i].input.length > maxLengthInput) {
maxLengthInput = data[i].input.length;
}
}
for (let i = 0; i < data.length; i++) {
data[i].input = normalizeArray(data[i].input);
}
return data;
}
const encode = d => {
const newArr = [];
d.split('').map(c => {
newArr.push((c.charCodeAt(0) / 255))
})
return newArr
}
const encodeData = data => {
return data.map( d => {
return {
input: encode(d.input),
output: d.output
}
})
}
const serializeAll = data => fixLengths(encodeData(data))
const serializeOne = data => normalizeArray(encode(data));
const trainData = [
...learnPhoneData,
...nonPhoneData
];
const net = new brain.NeuralNetwork({
activation: 'sigmoid', // activation function
hiddenLayers: [100, 100],
iterations: 2000,
learningRate: 0.002, // global learning rate, useful when training using streams
errorThresh: 0.005
});
net.train(serializeAll(trainData), {log: true})
//net.train(serializeAll(trainData))
// if entering only a phone number, it actually is very accurate :)
var output = net.run(serializeOne('07353 456357'))
console.log(output);
// {phone_number: 0.8490427059461814, non_phone_number: 0.149902567401934}
// when entering text and phone number, it is not accurate :-S
output = net.run(serializeOne('Call me on my 07353 456357 and I will get back ASAP.'))
console.log(output);
// {phone_number: 0.41922502546759033, non_phone_number: 0.5814407195666387}

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');
});

Categories

Resources