为了账号安全,请及时绑定邮箱和手机立即绑定

减少嵌套数组中的元素

减少嵌套数组中的元素

牛魔王的故事 2023-11-02 21:55:57
我正在尝试过滤数组并减少值,但我不知道如何操作。所以,我有一个示例数组[["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]如何创建一个带有 return 的函数[["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]]?你有什么主意吗?
查看完整描述

3 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您可以像这样将列表获取到页面。然后您可以在每个循环中按 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;

                    });

                }

            },

        });

    }


对象.条目


查看完整回答
反对 回复 2023-11-02
?
富国沪深

TA贡献1790条经验 获得超9个赞

您可以使用reduce和findIndex


const 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)


查看完整回答
反对 回复 2023-11-02
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

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;

}, {});

我们需要构建一个数组,同时减少另一个数组,如上所示。在每一步中,我们都会检查是否已经拥有该元素。如果没有,那么我们添加它。否则我们根据需要增加它。


查看完整回答
反对 回复 2023-11-02
  • 3 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信