数组查询部分
/**
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number}
*/
export default function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
let i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {// do not use === here, test fails
return i;
}
i++;
}
return -1;
}
}
使用
const data = [1,3,4,5,'chenjianbin',{id: 'ssd'},3,4,3,4,34,1]
console.log(inArray(data,‘chenjianbin’)) //返回 4
console.log(inArray(data,'ssd', 'id')) //返回 5
数组去重部分
/**
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
export default function uniqueArray(src, key, sort) {
let results = [];
let values = [];
let i = 0;
while (i < src.length) {
let val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort((a, b) => {
return a[key] > b[key];
});
}
}
return results;
}