当前位置:网站首页>JS array is de duplicated, the ID is the same, and a value is added and merged
JS array is de duplicated, the ID is the same, and a value is added and merged
2022-07-28 09:35:00 【Sister [email protected]】
Case study 1:
Suppose you need to deal with the array structure .
let arr =[
{
id:'1', value:10},
{
id:'1', value:20},
{
id:'2', value:10}
]
// The final desired array structure , same id, hold value Value addition
// let newArr=[
// {id:'1',value:30},
// {id:'2',value:20},
// ]
The implementation is simple , Write it down for later review
let idArr = [] // identical id Put in the same array
let resultArr = [] // The final result array
for(let i = 0;i < arr.length; i++){
let index = idArr.indexOf(arr[i].id)
if(index > -1){
// It's the same id exist , obtain index Index position
resultArr[index].value += arr[i].value // Take the same id Of value Add up
}else{
idArr.push(arr[i].id)
resultArr.push(arr[i])
}
}
Print the results 
If this kind of data is processed more in the project , We can Encapsulate in a way , Pass in array that will do .
import {
delSomeObjValue } from '@/utils/tool.ts'
const originArr = [
{
id: '1', value: 10 },
{
id: '1', value: 20 },
{
id: '2', value: 10 },
{
id: '88', value: 2 },
{
id: '88', value: 5 },
{
id: '20', value: 50 }
]
console.log(delSomeObjValue(originArr, 'id', 'value'))
//tool.ts
/* arr Array to process keyName Used to judge the same key name keyValue Key value for calculation */
export function delSomeObjValue(arr:any[], keyName:string, valueName:string) {
const idArr:any[] = [] // same id Put in the same array
const resultArr:any[] = [] // The final result array
for (let i = 0; i < arr.length; i++) {
const index = idArr.indexOf(arr[i][keyName])
if (index > -1) {
// It's the same id exist , obtain index Index position
resultArr[index][valueName] += arr[i][valueName] // Take the same id Of value Add up
} else {
idArr.push(arr[i][keyName])
console.log(idArr) // Print the results ['1', '2', '88', '20']
resultArr.push(arr[i])
}
}
return resultArr
}

Case study 2:
This is an online example , I think the idea is very good , For practice .
Suppose you need to deal with the array structure .
const originData = [
{
name: 'tony', id: '1', age: '20' },
{
name: 'jack', id: '2', age: '21' },
{
name: 'tony', id: '3', age: '50' },
{
name: 'jack', id: '4', age: '10' },
{
name: 'mark', id: '5', age: '22' },
{
name: 'mark', id: '6', age: '40' }
]
// The final desired array structure
// name Same item , Merge into an array object
//const afterData = [
//{name: "tony",origin: [{ name: "tony", id: "1", age: "20" },{ name: "tony", id: "3", age: "50" }]},
//{name: "jack",origin: [{ name: "jack", id: "2", age: "21" },{ name: "jack", id: "4", age: "10" }]},
// {name: "mark",origin: [{ name: "mark", id: "5", age: "22" },{ name: "mark", id: "6", age: "40" }]}
// ]
Merge implementation code :
onMounted(() => {
const originData = [
{
name: 'tony', id: '1', age: '20' },
{
name: 'jack', id: '2', age: '21' },
{
name: 'tony', id: '3', age: '50' },
{
name: 'jack', id: '4', age: '10' },
{
name: 'mark', id: '5', age: '22' },
{
name: 'mark', id: '6', age: '40' }
]
const nameArr = [] // Deposit name, Used to find out whether there is the same name The situation of
const resultData = [] // Merge result array
for (let i = 0; i < originData.length; i++) {
if (nameArr.indexOf(originData[i].name) === -1) {
// No same found name Words
resultData.push({
name: originData[i].name,
origin: [originData[i]]
})
nameArr.push(originData[i].name)
} else {
// It's the same name Merge objects
for (let j = 0; j < resultData.length; j++) {
if (resultData[j].name === originData[i].name) {
resultData[j].origin.push(originData[i])
break
}
}
}
}
console.log(resultData, 'console.log(resultData)')
})
Print the results :

I have written articles like merging and reorganizing arrays before ,vue Merge various types of data , Add data of the same type
版权声明
本文为[Sister [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/209/202207280829469230.html
边栏推荐
- 2.9.5 Ext JS的Object类型处理及便捷方法
- Talk to the father of MySQL: code completion at one time is a good programmer
- 2022 safety officer-b certificate examination simulated 100 questions and answers
- 2022高压电工考试模拟100题及模拟考试
- MQTT.js 入门教程:学习笔记
- How promise instance solves hell callback
- ArrayList内部原理解析
- How does gbase 8A use preprocessing to quickly insert data?
- 股指期货开户的条件和流程
- 【解决】ERROR in [eslint] ESLint is not a constructor
猜你喜欢

个人博客小程序

Alibaba cloud server setup and pagoda panel connection

RGB-T追踪——【多模态融合】Visible-Thermal UAV Tracking: A Large-Scale Benchmark and New Baseline

Promise学习笔记

IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望

What is cross domain? How to solve the cross domain problem?

OpenShift 4 - 使用 VerticalPodAutoscaler 优化应用资源 Request 和 Limit

The maximum recommended number of rows for MySQL is 2000W. Is it reliable?

Promise实例如何解决地狱回调

咸鱼ESP32实例—MQTT 点亮LED
随机推荐
《PyTorch深度学习实践》第九课多分类问题(手写数字MNIST)
[high number] high number plane solid geometry
FPGA开发学习开源网站汇总
How to use gbase C API in multithreaded environment?
JDBC连接数据库
LeetCode(剑指 Offer)- 50. 第一个只出现一次的字符
Openshift 4 - use verticalpodautoscaler to optimize application resource request and limit
Magic Bracelet-【群论】【Burnside引理】【矩阵快速幂】
IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望
ShardingSphere之分库分表概念介绍(二)
2022高压电工考试模拟100题及模拟考试
个人博客小程序
Introduction to shardingsphere's concept of sub database and sub table (2)
376. Swing sequence [greedy, dynamic planning -----]
Force deduction question (1) -- sum of two numbers
[multithreading] the underlying principle of println method
F - Jealous Two-二维逆序对
The cooperation between starfish OS and metabell is just the beginning
MySQL中各类型文件详解
opencv安装配置测试