[英]Javascript/Lodash dynamically add or remove array elements
let order = [
{ column1 : "asc" },
{ column2 : "desc" },
{ column3 : "asc" }
]
I need help implementing the following function:我需要帮助实现以下 function:
function sorting(columnName) {
// I'm losted
}
The business rule of the function is as follows: function的业务规则如下:
This is the algorithm, but I can't implement it because of my lack of JS/Lodash skills.这是算法,但由于我缺乏 JS/Lodash 技能,我无法实现它。
I thank you all.我谢谢大家。
Note: I'm not asking for the implementation, but maybe a guide regarding the functions that could better solve the issue in native Javascript or using Lodash.注意:我不是要求实现,而是关于可以更好地解决本机 Javascript 或使用 Lodash 问题的功能的指南。
I wrote some code to inspire you.我写了一些代码来激励你。 However it has a big catch : I changed the data structure used for 'order'.
但是它有一个很大的问题:我更改了用于“订单”的数据结构。 You will find out having the right data structure for the task is one of the most important things.
你会发现为任务拥有正确的数据结构是最重要的事情之一。 Sometimes the first step of an algorithm is creating a data structure that makes it easier/faster to implement the desired algorithm.
有时算法的第一步是创建一个数据结构,以便更容易/更快地实现所需的算法。 You probably are stuck with the order array and have to find a way to iterate it.
您可能被订单数组卡住了,必须找到一种迭代它的方法。
// Columns must be unique. let order = { "column1": "asc", "column2": "desc", "column3": "asc" }; // Keep only objects with value "asc" or "desc" can exist in the array. function sorting(columnName) { // If the column does not exist, it must receive the value "asc" and be inserted at the END of the array. if (order[columnName] === undefined) { order[columnName] = 'asc'; } // If the column has a value of "asc", it must be changed to "desc". else if (order[columnName] === 'asc') { order[columnName] = 'desc'; } // If the column has the value "desc", the object must be removed from the array. else if (order[columnName] === 'desc') { delete order[columnName]; } } // Tests console.log(order); sorting('column4'); console.log(order); sorting('column1'); console.log(order); sorting('column1'); console.log(order);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.