[英]Arrays of Objects - splice the highest value of all of the objects. Javascript
Can you help me with this logical issue?你能帮我解决这个逻辑问题吗?
I have an array that has Object tasks inside, each task has a number of days to complete.我有一个数组,里面有对象任务,每个任务都有很多天来完成。
I have a function that .shift() the first item from an array, however, I need it to take out the task Object that's 'time' value is highest.我有一个函数 .shift() 是数组中的第一项,但是,我需要它来取出“时间”值最高的任务对象。
const assignableTasks = [
{
title: 'Design Framework',
time: '5',
sequential: 0,
seqData: '',
},
{
title: 'Design UI',
time: '3',
sequential: 0,
seqData: '',
},
{
title: 'Design Software',
time: '10',
sequential: 1,
seqData: 'Design Framework',
},
],
That is the design of the Array.这就是 Array 的设计。
This is my function to take a task from the list and return it:这是我从列表中获取任务并返回它的函数:
const fetchNewTask = () => {
return assignableTasks.shift();
};
With the above data in Tasks, it should take Design Software, then Design Framework, then Design UI.有了上面Tasks中的数据,应该是设计软件,然后是设计框架,然后是设计UI。
Thank you in advance先感谢您
sort
your array by providing a custom compare
function to this array method.通过为此数组方法提供自定义
compare
函数来sort
数组进行sort
。 Then proceed with your shifting approach.然后继续你的转变方法。
Note笔记
Be aware that due to a task object's structure each time
property features the to be compared value as string value .请注意,由于任务对象的结构,每个
time
属性都将要比较的值作为字符串值。 Thus this value has to be explicitly casted into a number value in order to contribute to a correct (and non breaking) comparison result ...因此,必须将此值显式转换为数字值,以提供正确(且不中断)的比较结果......
function fetchNewTask(task) { // does mutate the original // array reference. return task .sort((a, b) => Number(b.time) - Number(a.time)) .shift(); }; const assignableTasks = [{ title: 'Design Framework', time: '5', sequential: 0, seqData: '', }, { title: 'Design UI', time: '3', sequential: 0, seqData: '', }, { title: 'Design Software', time: '10', sequential: 1, seqData: 'Design Framework', }]; console.log('assignableTasks :', assignableTasks); console.log('fetchNewTask(assignableTasks) :', fetchNewTask(assignableTasks)); console.log('assignableTasks :', assignableTasks);
.as-console-wrapper { min-height: 100%!important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.