'use?strict'
var?list?=?[
????{?products:?'products0',?price:?11,?amount:?10,?profit:?5?},
????{?products:?'products1',?price:?13,?amount:?55,?profit:?6?},
????{?products:?'products2',?price:?23,?amount:?105,?profit:?12?},
????{?products:?'products3',?price:?44,?amount:?40,?profit:?25?},
????{?products:?'products4',?price:?52,?amount:?20,?profit:?35?},
????{?products:?'products5',?price:?10,?amount:?66,?profit:?2?},
????{?products:?'products6',?price:?44,?amount:?34,?profit:?25?},
????{?products:?'products7',?price:?77,?amount:?77,?profit:?45?}
];
Array.prototype.sortby?=?function(key,?flag)?{?//?此方法只適用于當前這個問題
????return?this.slice(0).sort((a,?b)?=>?flag???b[key]?-?a[key]?:?a[key]?-?b[key]);
}
//?問題1:?將上面的數(shù)組改寫為:
var?list1?=?function()?{
????var?tempObj?=?{};
????for?(let?i?=?0;?i?<?list.length;?i++)?{
????????let?item?=?list[i];
????????for?(let?key?in?item)?{
????????????if?(!tempObj[key])?{?tempObj[key]?=?[]?}
????????????if?(!!tempObj[key]?&&?tempObj[key]?instanceof?Array)?{?tempObj[key].push(item[key])?}
????????}
????}
????return?tempObj;
}();
console.log('\r將上面的數(shù)組改寫為:?\r',?list1);
//?問題2?獲取其中最高和最低單價的產(chǎn)品
var?list2?=?list.sortby('price');
var?products2?=?{
????lowestPrice:?list2[0].products,
????highestPrice:?list2[list2.length?-?1].products
}
console.log('\r獲取其中最高和最低單價的產(chǎn)品:?',?products2);
//?問題3?按數(shù)量從高到低進行排序;
var?list3?=?list.sortby('amount',?true);
console.log('\r按數(shù)量從高到低進行排序:?\r',?list3);
//?問題4?獲取最大和最小總利潤的產(chǎn)品;
var?list4?=?list.sort((a,?b)?=>?{
????return?a['amount']?*?a['profit']?-?b['amount']?*?b['profit'];
});
var?products4?=?{
????minTotalProfit:?list4[0].products,
????maxTotalProfit:?list4[list4.length?-?1].products
}
console.log('\r獲取最大和最小總利潤的產(chǎn)品;',?products4);
/**?===================最終輸出結果如下===================
將上面的數(shù)組改寫為:?
?{?products:?
???[?'products0',
?????'products1',
?????'products2',
?????'products3',
?????'products4',
?????'products5',
?????'products6',
?????'products7'?],
??price:?[?11,?13,?23,?44,?52,?10,?44,?77?],
??amount:?[?10,?55,?105,?40,?20,?66,?34,?77?],
??profit:?[?5,?6,?12,?25,?35,?2,?25,?45?]?}
獲取其中最高和最低單價的產(chǎn)品:??{?lowestPrice:?'products5',?highestPrice:?'products7'?}
按數(shù)量從高到低進行排序:?
?[?{?products:?'products2',?price:?23,?amount:?105,?profit:?12?},
??{?products:?'products7',?price:?77,?amount:?77,?profit:?45?},
??{?products:?'products5',?price:?10,?amount:?66,?profit:?2?},
??{?products:?'products1',?price:?13,?amount:?55,?profit:?6?},
??{?products:?'products3',?price:?44,?amount:?40,?profit:?25?},
??{?products:?'products6',?price:?44,?amount:?34,?profit:?25?},
??{?products:?'products4',?price:?52,?amount:?20,?profit:?35?},
??{?products:?'products0',?price:?11,?amount:?10,?profit:?5?}?]
獲取最大和最小總利潤的產(chǎn)品;?{?minTotalProfit:?'products0',?maxTotalProfit:?'products7'?}
===============================================?**/