明月笑刀无情
您可以对数组应用二进制搜索。前提是您的数组已排序。->O(log(n))[obj1,obj2,obj3....obj100]测试中间的对象(obj50),然后决定是否必须在一半[obj1...obj49]或一半中进行搜索,[obj51...obj100]否则您可以将对象(事件)传递到其他数据结构中,例如树。->O(log(n)) 只是循环遍历整个数组不会有效率,但如果你不重复它太多也可以。但是从一开始就对数组进行排序将是最好的解决方案。编辑:以下代码显示了二进制搜索实现的基本示例。const events = [{ eventTitle: "Event title 1", eventId: "xyz1@google.com", startDate: "Sun Mar 18 00:00:00 GMT+01:00 2018", endDate: "Mon Mar 19 00:00:00 GMT+01:00 2018" }, { eventTitle: "Event title 2", eventId: "xyz2@google.com", startDate: "Tue Mar 19 00:00:00 GMT+01:00 2019", endDate: "Wed Mar 20 00:00:00 GMT+01:00 2019" }, { eventTitle: "Event title 3", eventId: "xyz3@google.com", startDate: "Fri Mar 20 00:00:00 GMT+01:00 2020", endDate: "Sat Mar 21 00:00:00 GMT+01:00 2020" }, { eventTitle: "Event title 4", eventId: "xyz4@google.com", startDate: "Fri Mar 21 00:00:00 GMT+01:00 2021", endDate: "Sat Mar 22 00:00:00 GMT+01:00 2021" }, { eventTitle: "Event title 5", eventId: "xyz5@google.com", startDate: "Fri Mar 22 00:00:00 GMT+01:00 2022", endDate: "Sat Mar 23 00:00:00 GMT+01:00 2022" }];function binarySearch(array, value, borderLeft, borderRight) { if (borderLeft <= borderRight) { var index = Math.floor((borderLeft + borderRight) / 2); var number = getNumberFromTitle(array[index].eventTitle); if (number == value) { return array[index].startDate; } else if (number > value) { return binarySearch(array, value, borderLeft, index - 1); } else { return binarySearch(array, value, index + 1, borderRight); } } else { return null; }}function getNumberFromTitle(title) { var tmp = title.split(" "); return tmp[tmp.length - 1];}console.log(binarySearch(events, 4, 0, events.length - 1));
哆啦的时光机
您可以创建映射器实用程序。首先,它会循环一次,O(n). 以后所有的电话都会O(1)我有工作代码:https://gist.github.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781function Mapper(array , key){ this.map = array.reduce(function(map, item){ var val = item[key]; if(!map[val]){ map[val] = []; } map[val].push(item); return map; },{});}Mapper.FIRST_INDEX = 0;Mapper.prototype.find = function find(key){ return this.map[key] && this.map[key][Mapper.FIRST_INDEX]//return blank array};Mapper.prototype.findAll = function find(key, returnUndefined){ return this.map[key] && this.map[key] || (returnUndefined? undefined: []);//return blank array};var users = [{eventTitle:"Event title 1", eventId:"xyz1@google.com", startDate:"Sun Mar 18 00:00:00 GMT+01:00 2018", endDate:"Mon Mar 19 00:00:00 GMT+01:00 2018"}, {eventTitle:"Event title 2", eventId:"xyz2@google.com", startDate:"Tue Mar 19 00:00:00 GMT+01:00 2019", endDate:"Wed Mar 20 00:00:00 GMT+01:00 2019"}, {eventTitle:"Event title 3", eventId:"xyz3@google.com", startDate:"Fri Mar 20 00:00:00 GMT+01:00 2020", endDate:"Sat Mar 21 00:00:00 GMT+01:00 2020"}];//How to usevar userMapper = new Mapper(users , 'eventTitle');console.log(userMapper.find("Event title 2")); var userToFind = ["Event title 3", "Event title 2"];var reqUsers = userToFind.map(function(name){ return userMapper.find(name);});console.log(reqUsers);