Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have two arrays:
sortKey: ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"]
and
receivedOrderKey: ["invoiceId", "orderId"]
I want to compare the above two arrays such that the result will contain all the values present in sortKey which matches partially with the values present in receivedOrderKey. For example: as receivedOrderKey contains invoiceId and orderId, the result should contain the following values from sortKey : "invoiceId-desc, "invoiceId-asc", "orderId-asc", "orderId-desc". I am presently using a two for loop solution to make this work. What would be an efficient way of doing this?
Code with for loops:
for(i=0;i<sortKey.length;i++){
var str1 = sortKey[i].toLowerCase();
for(j=0;j<receivedOrderKey.length;j++){
var str2 = receivedOrderKey[j].toLowerCase();
if(str1.includes(str2))
{
requestedOptions.push(sortKey[i]);
}
}
}
requestedOptions: ["orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc"]
Use filter
sortKey.filter( s => receivedOrderKey.indexOf( s.replace(/\-(asc|desc)/, "") ) != -1 );
Demo
var sortKey = ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"];
var receivedOrderKey = ["invoiceId", "orderId", "status"];
var fnCheck = ( item ) => receivedOrderKey.indexOf( item.replace(/\-(asc|desc)/, "") ) != -1;
var output = sortKey.filter( s => fnCheck(s) );
console.log( output );
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
So I have 2 arrays. One contains the colors of a product and on contains sizes of a product.
Let's say I have 2 colors (RED and BLUE), and 2 sizes (M and XL)
this right here is my jsx code:
{
sizeArray.map((size) => colorArray.map((color) => <input onChange={(e) => setCurrentQuantity(e.target.value)} placeholder={size + "/" + color}></input>))
}
So the code above creates 4 inputs like this:
input 1: BLUE/M
input 2: BLUE/XL
input 3: RED/M
input 4: RED/XL
My question is how do I save all the inputs as an object?
You can store an object in the state, with one key-value pair per input.
const [quantity, setQuantity] = useState({});
// ...
sizeArray.map((size) => colorArray.map((color) => <input
onChange={(e) => setQuantity(prev => ({...prev, [size+'/'+color] : e.target.value})}
value={quantity[size+'/'+color]} placeholder={size + "/" + color}/>))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I'm trying to find out how to get the average of change of the Profits/Losses variable
var profitLosses = [867884, 984655, 322013, -69417,
310503, 522857, 1033096, 604885, -216386, 477532,
893810, -80353, 779806, -335203, 697845, 793163,
485070, 584122, 62729, 668179, 899906, 834719, 132003];
I've used this code below to get the average, but I was wondering if there was a way to get the average of change for the period of time
var avg = (profitLosses / profitLosses.length) || 0;
console.log(avg)
I assume this is what you're looking for:
First you can calculate the changes using map, and putting 0 in the first value of the array.
Then you sum the changes using reduce.
Then you divide by the length-1 (because there are one less changes than there are profit&losses)
Also, with this code if your changes are for example +1 then -1 the average would be 0. If you want to look at absolute changes only, you'd have to use Math.abs(item) in the reduce function.
const profitLosses = [
867884, 984655, 322013, -69417, 310503, 522857, 1033096, 604885, -216386,
477532, 893810, -80353, 779806, -335203, 697845, 793163, 485070, 584122,
62729, 668179, 899906, 834719, 132003,
];
const changes = profitLosses.map((element, index) =>
index === 0 ? 0 : element - profitLosses[index - 1]
);
const total = profitLosses.reduce((acc, item) => acc + item, 0);
const averageChange = total / (profitLosses.length - 1);
console.log(averageChange);
Assuming Average of change is (sum of values in Array ProfitLosses / No. of values in the array).
First of all : (profitLosses / profitLosses.length) will give you NaN , I am confused how did you got the answer.
To get the answer you need the help of Array Methods ,specifically reduce method. To know more about Array Methods.
Below is the solution to your problem using the reduce method:
profitLosses.reduce( (sum , item) => sum += item, 0)/ profitLosses.length
``
Sum is the accumulator of the sum of array values : 11253418 (final value).
item : represents each value in the array.
Final aeverageChange : 489279.04347826086.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
I have an array
const databaseName = ['Oracle','Mysql','MongoDb'];
the expected output is
const database = [
{
name:'Oracle',
isAvailable:true
},
{
name:'Mysql',
isAvailable:true
},
{
name:'MongoDb',
isAvailable:true
}
]
This has to be done using Javascript and es6.
i have tried using
const database = {...databaseName ,isAvailable:true}
const databaseName = ['Oracle','Mysql','MongoDb'];
console.log(
databaseName.map(name => {
return {
name,
isAvailable:true
}
})
)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm getting data from an API and I want to filter the array down based on the issue state. The following code works, but is there a nice way to write this?
let issuesToUse = this.state.issues;
if(this.state.issueState.status === 'closed'){
issuesToUse = this.state.issues.filter(issue => {
return issue.state === 'closed';
})
} else {
issuesToUse = this.state.issues.filter(issue => {
return issue.state === 'open';
})
}
issuesToUse = this.state.issues.filter(issue => issue.state === this.state.issueState.status)
You could try something like this example
let targetState = this.state.issueState.status;
let issuesToUse = this.state.issues.filter(
({ state }) => state === targetState
);
See
Destructuring assignment
If you have other states as well, you need to check the state in advance for filtering.
let issuesToUse = this.state.issues;
if (['closed', 'open'].includs(this.state.issueState.status)) {
issuesToUse = this.state.issues.filter(({ state }) => state === this.state.issueState.status)
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to show the information I get from the user in pages with prev and next button, not on one page
I like to show every 5 elements on one page
const incomeItemShow = incomeContent.map(value => <SummaryItem key=
{value.id} money={value} func={props.money} />);
incomeContent is an Array and hold data i get from user Including an object {id: 0, check: "in", number: "12000", text: "sometext"}
What you tried so far?
If it would be me, at first glance I would create a property in the state, something like currentItemDisplayed, which is an array of two numbers. The first element is the index of the first element of incomeContentthat is displayed, while the second element is the index of the last element of incomeContent that is displayed.
Then, you display the two buttons, which will have onClick={this.back} and onClick={this.forward}, where these two functions could be something like:
back = () => {
const currentItemDisplayed = Object.assign([], this.state.currentItemDisplayed);
currentItemDisplayed[0] -= 5;
currentItemDisplayed[1] -= 5;
this.setState({currentItemDisplayed[0]});
}
forward = () => {
const currentItemDisplayed = Object.assign([], this.state.currentItemDisplayed);
currentItemDisplayed[0] += 5;
currentItemDisplayed[1] += 5;
this.setState({currentItemDisplayed[0]});
}
Be aware: you should cover the cases in which you are already displaying the first five elements and you click on the Back button. In that case, back() should not save [-5, 0] in the state, otherwise you will have error.
Finally, in the render() method you should write something like:
render() {
const currentItemDisplayed = this.state.currentItemDisplayed;
const itemToDisplay = incomeContent.slice(currentItemDisplayed[0], currentItemDisplayed[1]);
..
return (
..
{itemToDisplay.map(item => <SummaryItem ... /> )}
..
)
}
The idea would be to use an internal index to show the next items. It could look like this
const itemsToShow = incomeContent.slice(index, index + 5);
The buttons prev and next would increment/decrement the index by 5 or X. You might want to look into pagination which explains the concept of it.