预期输出应该类似[“Agri”,“水”]面积值应为[3,3] 我已尝试删除类别数组中的重复项,如果找到重复项,则应进行区域添加
<!DOCTYPE html>
<html>
<body>
<h1>Joining Two Arrays</h1>
<p id="demo"></p>
<script>
var twodim = new Array();
var category = ["Agri", "Agri","water"];
var area = [1, 2, 3];
for (n = 0; n < category.length; n=n+1)
{
twodim.push([category[n],area[n]]);
}
alert(twodim);
document.getElementById("demo").innerHTML = myChildren;
</script>
</body>
</html>
答案 0 :(得分:0)
你做得对。但是使用对象而不是数组。对象需要按键,易于按键是检测欺骗的简便方法。如果密钥存在,则执行添加。
var twodim = {}
var category = ["Agri", "Agri", "water"];
var area = [1, 2, 3];
for (var n = 0; n < category.length; n++) {
if (twodim[category[n]] === undefined) {
twodim[category[n]] = [category[n], area[n]]
} else {
twodim[category[n]][1] += area[n]
}
}
function getAsArray(obj) {
return Object.keys(obj).map(function(item) {
return obj[item];
});
}
console.log(twodim, getAsArray(twodim))
答案 1 :(得分:0)
我希望以下解决方案对您有所帮助。
您还可以在here
中查看此解决方案var new_cate = new Array();
var new_area = new Array();
var category = ["Agri", "Agri","water"];
var area = [1, 2, 3];
for (n = 0; n < category.length; n=n+1)
{
var IsFlag = false;
for(i=0;i<new_cate.length;i++){
if(new_cate[i] == category[n])
{
new_area[i] += area[n];
IsFlag = true;
}
}
if(!IsFlag)
{
new_cate.push(category[n]);
new_area.push(area[n]);
}
}
console.log(new_cate);
console.log(new_area);