数组归类与冒泡排序
2021-10-20 本文已影响0人
懵懵圈
//数组归类
var list = [
{
id: 1,
imei: '',
store_name: '合肥店'
},
{
id: 3,
imei: '3',
store_name: '合肥店'
},
{
id: 2,
imei: '1',
store_name: '芜湖店'
},
{
id: 4,
imei: '34343',
store_name: '上海店'
}
];
var data = [];
var map = {};
var dest = [];
for (let i = 0; i < list.length; i++) {
const element = list[i];
if (!data[element.store_name]) {
var arr = [];
arr.push(element)
data[element.store_name] = arr;
} else {
data[element.store_name].push(element)
}
}
console.log(data)
for (let i = 0; i < list.length; i++) {
const element = list[i];
if (!map[element.store_name]) {
dest.push({
store_name: element.store_name,
data: [element]
})
map[element.store_name] = element;
} else {
for (let j = 0; j < dest.length; j++) {
const element2 = dest[j];
if (element2.store_name == element.store_name) {
element2.data.push(element);
break;
}
}
}
}
console.log(dest)
//冒泡排序是指,每次比较相邻的两个值,如果前一个值比后一个大,就交换位置,这样第一次循环可以把最大的值排到最后,依次循环对比,可以达到排序的目的;
var arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
function sort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
console.log(sort(arr))