Jean717p edited in Tue, 30 Nov 2021

For example, var a = [1,2,3]; b = [4,5,6]; how can we get an array like [5,7,9] by adding two arrays.

7 Replies

```
a.map(function(item,index){
return item+b[index]
})
有很多种方式，你也可以for循环累加，`for in`，`Array.foreach`等
你的私信问题受字数限制
```

```
只能发到这边了
```

```
var result= array.reduce(function(initObj,item,index,array){
//根据条件进行分组
if(item.ab<100){
initObj.a100.push(item)
}
if(100<=item.ab&&item.ab<1000){
console.log(`满足100-1000,${item.ab}`)
initObj.a1000.push(item)
}
if(1000<=item.ab&&item.ab<10000){
initObj.a10000.push(item)
}
if(10000<=item.ab&&item.ab<100000){
initObj.a100000.push(item)
}
if(100000<=item.ab&&item.ab<1000000){
initObj.a1000000.push(item)
}
//根据分组按从小到大排序
return initObj;
},{a10:[],a100:[],a1000:[],a10000:[],a100000:[],a1000000:[]})
var finnalResult=[];
for(var index in result){
result[index].sort(function(itema,itemb){
return itema.ab-itemb.ab
})
finnalResult.push(result[index].shift())
}
return finnalResult.splice(0,1)
```

- If you want to use a var / let to define multiple variables, be careful not to write a comma as a semicolon.
- The program is simplelet a=[1,2,3], b=[4,5,6];let s = a.map(function(v, i) {return v + b[i];});console.log (s);

Add it in cycles;

```
var a=[1,2,3];
var b=[4,5,6];
var sumArray = [];
const bLength = b.length;
const aLength = a.length;
if (aLength < bLength) {
[a, b] = [b, a]
}
for (let index in a) {
if (index < bLength) {
sumArray[index] = a[index] + b[index]
} else {
sumArray[index] = a[index]
}
}
```

a= [1,2,3];b=[2,3,4];n = new Set([...a,...b]);x = [...n]//[1, 2, 3, 4]

Thank you for your invitation

It is suggested to analyze the problems first.

- What is the input? Two arrays [1,2,3] and [4,5,6].
- What is the output? A new array [5,7,9].

If you want to write a function, you already have parameters and returns. Next, how can I get the output from the input?

- From this point of view, two arrays with the same subscript can be added to get the new array with the same subscript.

Yes, that's the algorithm. Next, what can be done?

- After talking about arrays for a long time, I naturally give priority to the part of array standard library in JavaScript. In addition, the basic knowledge of program flow and operator is also indispensable.

Well, that's about it. It may be clumsy to write at the beginning. It's OK. You can optimize it over and over again. Practice makes perfect. The program is almost written, so I won't repeat it.

Last but not least, be careful!

For example, the title mentioned:

var a=[1,2,3];b=[4,5,6];

Here, you should pay attention to the semicolon in the middle. You need to use comma when batch assignment. In strict mode, you need to report an error.