有一个名为householdArray
的数组,其中填充了具有两个属性的对象:第一个是isSelling
,其值是true
或false
。第二个是askingPrice
,其值是一个数字。还有另一个名为buyer
的对象,该对象具有带数字值的budget
属性。
如何在isSelling === true
中所有具有householdArray
的对象中找到askingPrice
最高的buyer
,该对象位于budget
的中?
最佳答案
您可以使用过滤器和min max,但我会通过使用Array.prototype.reduce()
在O(n)时间内一次完成此工作。为了鼓励您使用箭头功能,我将首先向您展示箭头,然后再向您展示常规功能的实现。
请注意,我们将{isSelling: true, askingPrice: 0}
之类的对象用作reduce操作的初始值。
var buyer = {budget:1000},
household = [{ isSelling: true,
askingPrice: 500},
{ isSelling: false,
askingPrice: 500},
{ isSelling: true,
askingPrice: 1000},
{ isSelling: true,
askingPrice: 790},
{ isSelling: false,
askingPrice: 1000},
{ isSelling: true,
askingPrice: 1200},
{ isSelling: false,
askingPrice: 690},
{ isSelling: true,
askingPrice: 890},
{ isSelling: true,
askingPrice: 1500},
{ isSelling: true,
askingPrice: 790},
{ isSelling: true,
askingPrice: 900},
{ isSelling: true,
askingPrice: 990},
{ isSelling: false,
askingPrice: 990},
{ isSelling: true,
askingPrice: 670}
],
result = household.reduce((p,c) => c.isSelling === true &&
c.askingPrice <= buyer.budget &&
c.askingPrice > p.askingPrice ? c : p,{isSelling: true, askingPrice: 0});
console.log(result);
现在有了常规功能实现
var buyer = {budget:1000},
household = [{ isSelling: true,
askingPrice: 500},
{ isSelling: false,
askingPrice: 500},
{ isSelling: true,
askingPrice: 670},
{ isSelling: true,
askingPrice: 790},
{ isSelling: false,
askingPrice: 1000},
{ isSelling: true,
askingPrice: 1200},
{ isSelling: false,
askingPrice: 690},
{ isSelling: true,
askingPrice: 890},
{ isSelling: true,
askingPrice: 1500},
{ isSelling: true,
askingPrice: 790},
{ isSelling: true,
askingPrice: 900},
{ isSelling: true,
askingPrice: 990},
{ isSelling: false,
askingPrice: 990},
{ isSelling: true,
askingPrice: 1000}
],
result = household.reduce(function(p,c){
return c.isSelling === true &&
c.askingPrice <= buyer.budget &&
c.askingPrice > p.askingPrice ? c : p
},{isSelling: true, askingPrice: 0});
console.log(result);
并且,如果您想获取符合我们条件的记录索引,只需将index参数添加到reduce的回调中,并使用初始值“ 0”,如下所示;
var buyer = {budget:1000},
household = [{ isSelling: false,
askingPrice: 1500},
{ isSelling: false,
askingPrice: 500},
{ isSelling: true,
askingPrice: 1000},
{ isSelling: true,
askingPrice: 670},
{ isSelling: true,
askingPrice: 790},
{ isSelling: false,
askingPrice: 1000},
{ isSelling: true,
askingPrice: 1200},
{ isSelling: false,
askingPrice: 690},
{ isSelling: true,
askingPrice: 890},
{ isSelling: true,
askingPrice: 1500},
{ isSelling: true,
askingPrice: 790},
{ isSelling: true,
askingPrice: 900},
{ isSelling: true,
askingPrice: 990},
{ isSelling: false,
askingPrice: 990}
],
result = household.reduce(function(p,c,i,a){
return a[p].isSelling === false ||
a[p].askingPrice > buyer.budget ||
c.isSelling === true &&
c.askingPrice <= buyer.budget &&
c.askingPrice > a[p].askingPrice ? i : p;
},0);
result = household[result].isSelling === true && household[result].askingPrice <= buyer.budget ? result : -1;
console.log(result);