减少嵌套数组中的元素

我正在尝试过滤数组并减少值,但我不知道如何操作。

所以,我有一个示例数组[["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]

如何创建一个带有 return 的函数[["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]]

你有什么主意吗?


牛魔王的故事
浏览 75回答 3
3回答

眼眸繁星

您可以像这样将列表获取到页面。然后您可以在每个循环中按 div 或 ul 列表内部。function findEmployees(userCounty) {        $.ajax({            type: "POST",            dataType: "json",            url: '@Url.Action("getCounty", "Contact")',            data: JSON.stringify(userCounty),            contentType: "application/json",            success: function (result) {                if (result.data.length !== 0) {                    $.each(result.data, function (index, value) {                        var firstName = value.firstName;                        var lastName = value.lastName;                    });                }            },        });    }对象.条目

富国沪深

您可以使用reduce和findIndexconst list = [  ["Hampton Tricep Rope", 3],  ["Chrome Curl Bar", 8],  ["Hampton Tricep Rope", 6]].reduce((acc, x) => {  const index = acc.findIndex(y => y[0] === x[0]);  if (index >= 0) {    acc[index][1] += x[1];    return acc;  }  acc.push(x);  return acc;}, [])console.log(list)

慕虎7371278

var result = [];[["Hampton Tricep Rope", 3],["Chrome Curl Bar",8],["Hampton Tricep Rope", 6]].reduce(function(res, value) {  if (!result.filter((item) => (item[0] === value[0])).length) {    result.push([value[0], value[1]]);  } else {    result.filter((item) => (item[0] === value[0]))[0][1] += value[1];  }  return res;}, {});我们需要构建一个数组,同时减少另一个数组,如上所示。在每一步中,我们都会检查是否已经拥有该元素。如果没有,那么我们添加它。否则我们根据需要增加它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript