Array object deduplication based on id (javascript method)

Array object deduplication based on id (javascript method)

Example: Array object that needs to be deduplicated

	let arr = [
		{
    
     duty: "Web前端工程师", id: "aiWXizrJyWK9Vrzbg2L", orgName: "研发部" },
		{
    
     duty: "Web前端工程师", id: "aiWXizrJyWK9Vrzbg2L", orgName: "研发部" },
		{
    
     duty: "测试工程师", id: "A1l1XNCpDVEPqpR8qM0", orgName: "研发部" },
		{
    
     duty: "产品工程师", id: "xbY1eRH8HC0OaxKK38S", orgName: "项目部" },
		{
    
     duty: "会计", id: "djDeiYHzuNckCrs6VCK", orgName: "财务部" },
	]

method one

Traverse through the for loop, and then use the some method to determine whether the current object id is included, otherwise add

	let forData = [];
	for (let i = 0; i < arr.length; i++) {
    
    
	  if (!forData.some(e => e.id == arr[i].id)) forData.push(arr[i]);
	}
	console.log("输出结果:", forData)

Method Two

Similar to method 1, replace the forEach method with the for loop traversal, and then use the some method to determine

	let forData = [];
	arr.forEach(item => {
    
    
	  if (!forData.some(e => e.id == item.id)) forData.push(item);
	})
	console.log("输出结果:", forData)

Method three

Similar to method two, also use the forEach method to loop through, and replace the find method with the some method to determine

	let forData = [];
	arr.forEach(item => {
    
    
	  if (!forData.find(e => e.id == item.id)) forData.push(item);
	})
	console.log("输出结果:", forData)

Method 4 (high-order method)

Through the reduce method and the defined obj, determine whether obj[currentValue.id] exists, otherwise add the object

	let obj = {
    
    }
	let forData = []
	forData = arr.reduce((total, currentValue) => {
    
    
		obj[currentValue.id] ? '' : (obj[currentValue.id] = true && total.push(currentValue))
		return total
	}, [])
	console.log("输出结果:", forData)

Guess you like

Origin blog.csdn.net/TurtleOrange/article/details/126519844