Javascript Return Conditionals - javascript
searchList(array, filters) {
var currentUserId = 125;
var list = array;
// array example [{aisle: A9, userid: 125},{aisle: B2, userid: null},{aisle: C#, userid: 125}]
// filters example {assignedButtonActive: true, unassignedButtonActive: false, aisle: A9}
result = Object.keys(list)
.map((key) => {
return { ...list[key] };
})
.filter((data) => {
// If assigned or unassigned buttons are not active, this filter doesnt apply and aisle should be the only thing filtering
let assigned = filters.assignedButtonActive
let unassigned = filters.unassignedButtonActive
let aisleSelection = filter.aisle;
let aisle = data.aisle;
let userid = data.userid;
return aisle.indexOf(aisleSelection) > -1 // Need a conditional to also filter out assigned/unassigned if the buttons are active, otherwise not needed.
});
return result;
}
I am trying to filter a list with the combination of an input search and button/flags. I have no problem with the input search function filtering and returning the list. The problem Im having is using boolean flags along with the search input to be even more exact on what i want to filter, but I am having an issue on how to return the result using conditionals/booleans in this case. I cant seem to mix the two conditions for a return with both filters applied. I've tried something like this return aisle.indexOf(aisleSelection) > -1 && (assigned) ? assignedTo == currentUserId : (unassigned) ? assignedTo == null : [] but seems I'm way off. For example if either assigned/unassigned flags are active, it will add one of these two filters assignedTo === currentUserId or assignedTo == null to filter along with aisle filter as well, pretty much so they can work together as well, not one or the other
Not looking for the solution written out for me, more on how I can handle this filtering beyond just an input, with the possibility to off more filters being used
Any help/tips would be greatly appreciated
Finish out the function before returning, then have different return statements for each condition
rather than
return aisle.indexOf(aisleSelection) > -1
try
if (aisle.indexOf(aisleSelection) > -1) {
return true}
else if (other possibility){
return true}
else (case to filter out){
return false}
filter gets called on each element in the array, and decides to keep the element if the callback function returns true
Based on what I have understood, follow through this code especially the part I have commented then let me know if this what you wanted. If there's you don't get, let me know.
function searchList(array, filters) {
var currentUserId = 125;
var list = array;
result = Object.keys(list)
.map((key) => ({ ...list[key] }))
.filter((data) => {
let assignedSelection = filters.assignedButtonActive;
let unassignedSelection = filters.unassignedButtonActive;
let aisleSelection = filters.aisle;
let aisle = data.aisle;
let userid = data.userid;
return Boolean(Boolean(assignedSelection) || Boolean(unassignedSelection)) && aisle.includes(aisleSelection)?assignedTo = currentUserId:assignedTo = null;
/**
Explanation:
I am not sure of what you wanted to achieve with this, but follow through and see If this is what you wanted.
1. Boolean(Boolean(assignedSelection) || Boolean(unassignedSelection))
This part will return true if either assignedSelection or unassignedSelection is true.
This part will return false if both assignedSelection and unassignedSelection are false.
2. aisle.includes(aisleSelection)
This part will return true if aisleSelection matches aisle
This part will return false if aisleSelection does not match aisle
3. Boolean(Boolean(assignedSelection) || Boolean(unassignedSelection)) && aisle.includes(aisleSelection)
This part will return true if both part_(1) and part_(2) return true
Thus part will return false if either part_(1) or part_(2) returns false
4. return Boolean(Boolean(assignedSelection) || Boolean(unassignedSelection)) && aisle.includes(aisleSelection)? assignedTo = currentUserId : assignedTo = null;
This part will return null if part_(3) returns false
This part will give the variable assignedTo the value currentUserId if part_(3) returns true
*/
});
return result;
}
//Execute the example
var arrayExample = [
{ aisle: "A9", userid: 125 },
{ aisle: "B2", userid: null },
{ aisle: "C#", userid: 126 },
];
var filtersExample = {
assignedButtonActive: true,
unassignedButtonActive: false,
aisle: "A9",
};
searchList(arrayExample, filtersExample);
in such cases, I use the usual brackets to show the individual parts of the inequality. example
return aisle.indexOf(aisleSelection) > -1 && (assigned) ? assignedTo == currentUserId : ((unassigned) ? assignedTo == null : [])
but maybe
return assignedTo = (aisle.indexOf(aisleSelection) > -1 && (assigned) ? currentUserId : ((unassigned) ? null : []))
I may have misunderstood the necessary conditions. if you describe the conditions in more detail, the answer will be more correct.
Related
MySQL conditional filters handling
I am using node.js and trying to query based on multiple filters if only they are true select * from orders ${isFilter ? 'where' : ''} ${orderId !== undefined && orderId ? `order_id = '${orderId}' or ` : '' } ${receiptId !== undefined && receiptId? `receipt_id = '${receiptId}' or `: '' } ${driver !== undefined && driver ? `driver_id = '${Number(driver)}'` : '' } this works fine where there is no filter or when all the filters are true but the OR causes an issue when one filter or more are missing. what would be the best way to handle this ?
This is a pseudo code to dynamically compose the query var clause = 'where'; var query = 'select * from orders'; if (isFilter) { // this statement could be removed if (orderId !== undefined && orderId) { query += clause + ' order_id = `${orderId}`'; clause = 'or'; } if (receiptId !== undefined && receiptId) { query += clause + ' receiptId = `${receiptId}`'; clause = 'or'; } if (driver !== undefined && driver) { query += clause + ' driver = `${driver}`'; clause = 'or'; // this is not really needed, but it could be useful for further filters in future } }
let whereClause = []; if(orderId) whereClause.push(`order_id = '${orderId}'`); if(receiptId) whereClause.push(`receipt_id = '${receiptId}'`); if(driver) whereClause.push(`driver_id = ${parseInt(driver)}`); let whereQuery = whereClause.join(' OR '); let sql = `select * from orders where true ${whereClause.length ? whereQuery : ''}`; try using join. so that you can add many properties even not in order. Also if you're expecting it to be undefined, then you may remove that as it resulted false on condition statement.
I think it would be reasonable if you can log the query. we can be sure about the query that's being sent. This would be the first step to troubleshoot and may be we can use the way you are trying using ternary operator with few changes.
The code you used above to build the query string is not possible to cover all possible cases. Example: What if isFilter==false and one of the 3 variables orderId, receiptId and driver has the value !== undefined? => your query will be wrong because the WHERE statement is missing. Another case, if one of the variables orderId or receiptId satisfied the condition and the variable driver is not valid. => Your query will be wrong because of the extra of 'OR' at the end. Those are the 2 cases that are most likely to cause problems for the above code. Here is my suggestion to solve your problem: queryString="select * from orders" if(isFilter){ queryString+=' where' if(orderId){ queryString+=' ..... or' } if(receiptId){ queryString+=' ..... or' } if(driver){ queryString+=' .....' } } queryString=queryString.trim() if(queryString.endsWith('or')){ queryString=queryString.substring(0,queryString.length-2) } if(queryString.endsWith('where')){ queryString=queryString.substring(0,queryString.length-5) }
select * from orders ${isFilter ? 'where 1=0' : ''} ${orderId !== undefined && orderId ? `OR order_id = '${orderId}' ` : '' } ${receiptId !== undefined && receiptId? `OR receipt_id = '${receiptId}' `: '' } ${driver !== undefined && driver ? `OR driver_id = '${Number(driver)}'` : '' } Instead if its AND you can do 1=1 instead of 1=0.
How to filter values of an array inside an array?
I will describe the situation for more clarity. I have an array like this animalsArray = { animalID : number, animalName: string, animalDescription: string, animalChild: animalsArray[] } Now I have to filter these animals using animalName from user input by textfield. Some animals can have n number of animalChild or non at all or animalChild can have another animalChild inside it. I already have a code like this public animalsArray:animalsArray[] this.filteredanimalsArray.next( this.animalsArray.filter(item => (item.animalName.toLowerCase().indexOf(search) > -1)) ); To filter the main animalsArray and it works fine but the user input doesn't go through the child arrays. How can I solve this problem? Thanks in advance
Maybe you could use recursivity like this : function filterAnimals(animals, name) { return animals.filter(animal => { const matching = animal.animalName.toLowerCase() === name.toLowerCase(); const hasChildMatch = Array.isArray(animal.animalChild) && filterAnimals(animal.animalChild, name).length > 0; return matching || hasChildMatch; }); } const search = 'leon'; const filterdAnimals = filterAnimals(animalsArray, search);
Check for certain value in every key of a Javascript object
I have the following line: <button className={`actionBoxButton ${props.moves[0].moveName !== "FirstPassMove" && props.moves[0].moveName !== "PassMove" ? "actionBoxButtonGrey" : ''}`} What it does is to check if the object "moves" has the value "FirstPassMove" for the key moveName. If so, I want it so switch to another style. This is working well. But what I want to achieve is, to not only check the element 0 of the object, but all the objects and check if there is a moveName "FirstPassMove" in any element of the object. It is written in React 16.12 Thanks!
You can simplify your jsx by defining a separate function for dynamic className like this: const check = () => { let className_ = ""; // if this.props.moves is an array, use of instead of in for(let i in this.props.moves) { if((this.props.moves[i].moveName !== "FirstPassMove") && (this.props.moves[i].moveName !== "PassMove")) { className_ = "actionBoxButtonGrey"; } } return className_; } <button className={this.check()}>button</button>
props.moves.includes('FirstPassMove') Assuming your props.moves is an array it will return true or false if this string is inside the props.moves array
If you want to add className in case at least one of your moves has FirstPassMove or PassMove name you should use Array.prototype.some() const hasPass = moves.some(({ moveName }) => ( moveName === "FirstPassMove" || moveName === "PassMove" ));
I am guessing you want to check that all the moves satisfy the constraint, in which case, you can use Array.prototype.every to ensure every move satisfies the constraint. If you only need some moves to satisfy the constraint, you may use Array.prototype.some instead. // For example const props = { moves: [ { moveName: 'FirstPassMove' }, { moveName: 'PassMove' }, { moveName: 'PassMove' }, { moveName: 'OtherPassMove' }, ] }; function isValidMove({ moveName }) { return moveName !== "FirstPassMove" && moveName !== "PassMove"; } function getActionBoxButtonClassName(hasColor) { return `actionBoxButton ${hasColor ? "actionBoxButtonGrey" : ''}`; } console.log([ getActionBoxButtonClassName(props.moves.every(isValidMove)), getActionBoxButtonClassName(props.moves.some(isValidMove)) ]);
how to search through the array and return the matching value
I have an array of some class names that all of the values in that array end with numbers. I want to have a function that when I give it a number, it search through that array, and check the last 3 digits of each value, to find the matching number and return that matching value. So lets say, I give it value 200 and it searches through the array and returns wi-owm-200. I manage to make it but it does not return it. It does find the value, but when it is outside of the function, it returns 'undefined'. Here is my code: Fiddle var owmIcon = ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"]; var res = findOWMIcon("200"); console.log(res); function findOWMIcon(num) { $.each(owmIcon, function(key, value) { var classNum = value.substr(value.length - 3); if (parseInt(num, 10) === parseInt(classNum, 10)) { console.log(value); return value; } }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Any idea how to solve it? So I can get the found value outside the function?
This is sufficient: owmIcon.filter(e => e.slice(-3) == "200"); // Get all elements that ends in "01" items = get_all_items().filter(e => e.slice(-2) == "01"); console.log(items); function get_all_items(){ return ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"]; } Use function(e){ return e.slice(-3) == "200"; } instead of e => ... if you care about backward compatibility (ES5 and before).
let data = ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"]; // Suppose you want to get all elements that end with 200, so... let filteredData = data.filter(item => item.slice(-3) === "200"); console.log(filteredData);
filtering an element from object array
I have an array of object something like below Object[0] canUpload:false canBeRemoved:true type:Object allowMultiple:false deleted:false key:"testValue" Object[1] canUpload:true canBeRemoved:true type:Object allowMultiple:false deleted:false key:"testValue2" I want to remove an elements from array which contains key:testValue var myValues = this.testData.data3; if(!this.testData.canDownload){ myValues= myValues.filter(function(value){ if(!value.canUpload) return value.type.key==='testValue'; else return false; }); But its not removing .Whats the right way to do it? Here is the full code .I can see myValues array of size 2 .If i print myValues after if block its empty. Code pen:http://codepen.io/developer301985/pen/woGBNg
If your want to filter your array on the basis of two conditions: canUpload attr is false type.key is equal to 'testValue' so you may want to return false in case of canUpload is true to be as follow: myValues= myValues.filter(function(value) { if(!value.canUpload) return value.type.key === 'testValue'; else return false; }); Otherwise, you just want to filter on type.key is equal to 'testValue', so it will be as follow: myValues= myValues.filter(function(value) { return value.type.key === 'testValue'; });
Note, if the callback function you passed into filter returns true, the element will be kept rather than removed. So in your case, you should return false when the value is testValue. If I understand you correctly, you want to remove item with value.canUpload==false AND type.key === 'testValue'. Then the negate is value.canUpload || value.type.key !== 'testValue' var myValues = this.testData.data3; if (!this.testData.canDownload) { myValues = myValues.filter(function(value) { return value.canUpload || value.type.key !== 'testValue'; }); } Let me know whether it works :)