1,对象数组去重
/**
* 对象数组去重
* arr 数组
* prop 属性键值:name 根据name去重
*/
const ARR_DISTINCT_BY_PROP = function(arr, prop) {
const obj = {}
return arr.reduce(function(preValue, item) {
if (!obj[item[prop]]) {
obj[item[prop]] = true && preValue.push(item)
}
return preValue
}, [])
}
2,用js实现将二维数组格式化转换成树状数组
/** 用js实现将二维数组格式化转换成树状数组
* arr = [
["a", "aa", "aaa", "aaaa"],
["b", "bb", "bbb"],]
*/
export const makeData = function(arr) {
const obj = {}
const res = []
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
const item = arr[i][j]
const key =
item.name + '-' + item.parentName + '-' + item.firstName + '-' + j
if (!obj[key]) {
obj[key] = {
name: item.name,
value: item.value,
firstName: item.firstName,
parentName: item.parentName,
formatter: item.formatter,
number: j,
children: []
}
}
if (j > 0) {
const length =
arr[i][j - 1].name +
'-' +
arr[i][j - 1].parentName +
'-' +
arr[i][j - 1].firstName +
'-' +
(j - 1)
const parent = obj[length]
if (parent) {
if (parent.children.indexOf(obj[key]) < 0) {
parent.children.push(obj[key])
}
}
} else if (res.indexOf(obj[key]) < 0) {
res.push(obj[key])
}
}
}
return res
}
3,将树结构数据转换为一维数组
// 将树结构数据转换为一维数组
export const flatTree = function(arr, result = []) {
arr.map((item, key) => {
if (item.number > 0) {
result.push({
source: item.parentName,
target: item.name,
value: item.value,
formatter: item.formatter,
number: item.number
})
}
if (item.children && item.children.length > 0) {
flatTree(item.children, result)
}
})
return result
}
4, 数组去重
// 数组去重
unique(array) {
const r = []
for (let i = 0, l = array.length; i < l; i++) {
for (let j = i + 1; j < l; j++)
if (array[i] === array[j]) {
j = ++i
}
r.push(array[i])
}
return r
}
网友评论