【问题标题】:how to order arrangements based on a condition in javascript?如何根据javascript中的条件订购安排?
【发布时间】:2020-10-10 06:02:46
【问题描述】:

我有一个结构,其中排列的数量可以变化:

array1 = [
{local: {id: 1, name: 'local1'}},
{local: {id: 2, name: 'local2'}},
{local: {id: 3, name: 'local3'}},
{local: {id: 4, name: 'local4'}},
{local: {id: 5, name: 'local5'}}
];

array2 = [
{local: {id: 1, name: 'local1'}},
{local: {id: 3, name: 'local3'}},
{local: {id: 3, name: 'local4'}},
{local: {id: 3, name: 'local5'}},
];

array3 = [
{local: {id: 1, name: 'local1'}},
{local: {id: 3, name: 'local2'}},
{local: {id: 3, name: 'local3'}},
{local: {id: 3, name: 'local5'}},
];

我需要从这些创建一个新数组,其中这个新数组首先按在所有数组中重复的 id 排序,然后是不重复的,应该是这样的:

newArray = [
    {local: {id: 1, name: 'local1'}},
    {local: {id: 3, name: 'local3'}},
    {local: {id: 5, name: 'local5'}},
    {local: {id: 2, name: 'local2'}},
    {local: {id: 4, name: 'local4'}}
  ]

谁能帮帮我!!

【问题讨论】:

  • 对于重复的 id 情况,您希望将所有数组中的哪个元素推送到结果数组中。
  • 对于所有相似的 id,name 的值是否相同?
  • 到目前为止您尝试过什么?你研究过你的问题吗?我在您的问题中没有看到任何代码尝试。虽然我们都渴望提供帮助,但同样重要的是要注意 Stack Overflow 不是编码服务。请向我们展示您迄今为止所做的尝试,以便我们可以为您指明正确的方向。

标签: javascript arrays sorting dictionary filter


【解决方案1】:

将所有数组转换为对象以便快速搜索。

const array1 = [{
    local: {
      id: 1,
      name: 'local1'
    }
  },
  {
    local: {
      id: 2,
      name: 'local2'
    }
  },
  {
    local: {
      id: 3,
      name: 'local3'
    }
  },
  {
    local: {
      id: 4,
      name: 'local4'
    }
  },
  {
    local: {
      id: 5,
      name: 'local5'
    }
  }
];

const array2 = [{
    local: {
      id: 1,
      name: 'local1'
    }
  },
  {
    local: {
      id: 3,
      name: 'local3'
    }
  },
  {
    local: {
      id: 3,
      name: 'local4'
    }
  },
  {
    local: {
      id: 3,
      name: 'local5'
    }
  },
];

const array3 = [{
    local: {
      id: 1,
      name: 'local1'
    }
  },
  {
    local: {
      id: 3,
      name: 'local2'
    }
  },
  {
    local: {
      id: 3,
      name: 'local3'
    }
  },
  {
    local: {
      id: 3,
      name: 'local5'
    }
  },
];

const obj1 = array1.reduce((acc, item) => {
  acc[item.local.id] = item;
  return acc;
}, {});

const obj2 = array2.reduce((acc, item) => {
  acc[item.local.id] = item;
  return acc;
}, {});


const obj3 = array3.reduce((acc, item) => {
  acc[item.local.id] = item;
  return acc;
}, {});

const result = {
  ...obj3,
  ...obj2,
  ...obj1
};

const output = [];
const temp = [];

for (let key in result) {
  if (obj1[key] && obj2[key] && obj3[key]) {
    output.push(result[key]);
  } else temp.push(result[key]);
}

console.log([...output, ...temp]);

【讨论】:

    【解决方案2】:

    我会这样做(可能不是最佳解决方案):

    /* Same Arrays as yours */ const array1=[{local:{id:1,name:"local1"}},{local:{id:2,name:"local2"}},{local:{id:3,name:"local3"}},{local:{id:4,name:"local4"}},{local:{id:5,name:"local5"}}],array2=[{local:{id:1,name:"local1"}},{local:{id:3,name:"local3"}},{local:{id:3,name:"local4"}},{local:{id:3,name:"local5"}}],array3=[{local:{id:1,name:"local1"}},{local:{id:3,name:"local2"}},{local:{id:3,name:"local3"}},{local:{id:3,name:"local5"}}];
    
    function myFunc(arrays) {
      // All items, with duplicates
      const allItems = [].concat.apply([], arrays);
      // All IDs, without duplicates thanks to `Set`
      const allIDs = Array.from(
        allItems.reduce((set, item) => set.add(item.local.id), new Set())
      );
      
      // Helper function used for sorting
      const isInAllArrays = id => arrays.every(
        arr => arr.some(item => item.local.id === id)
      );
      // Sort the IDs based on whether they are in all arrays or not
      allIDs.sort((a, b) => {
        const _a = isInAllArrays(a), _b = isInAllArrays(b);
        if (_a !== _b) return _a ? -1 : 1;
        return 0;
      });
      // Map all IDs to the first element with this ID
      return allIDs.map(id => allItems.find(item => item.local.id === id));
    }
    
    const newArray = myFunc([array1, array2, array3]);
    
    // Just for readability in the demo below
    console.log(JSON.stringify(newArray).split('},{').join('},\n{'));

    【讨论】:

      【解决方案3】:

      1) 遍历所有数组并构建一个对象,其键为id,值包括对象,并保持出现频率(计数)。 2) 现在,上述对象的Object.values 并根据“计数”对它们进行排序。 您将在顶部获得最常见的项目。

      const sort = (...arrs) => {
        const all = {};
        arrs
          .flat()
          .forEach(
            (obj) =>
              (all[obj.local.id] =
                obj.local.id in all
                  ? { ...all[obj.local.id], count: all[obj.local.id].count + 1 }
                  : { ...obj, count: 1 })
          );
        return Object.values(all)
          .sort((a, b) => b.count - a.count)
          .map(({ count, ...rest }) => rest);
      };
      
      array1 = [
        { local: { id: 1, name: "local1" } },
        { local: { id: 2, name: "local2" } },
        { local: { id: 3, name: "local3" } },
        { local: { id: 4, name: "local4" } },
        { local: { id: 5, name: "local5" } },
      ];
      
      array2 = [
        { local: { id: 1, name: "local1" } },
        { local: { id: 3, name: "local3" } },
        { local: { id: 3, name: "local4" } },
        { local: { id: 3, name: "local5" } },
      ];
      
      array3 = [
        { local: { id: 1, name: "local1" } },
        { local: { id: 3, name: "local2" } },
        { local: { id: 3, name: "local3" } },
        { local: { id: 3, name: "local5" } },
      ];
      
      
      console.log(sort(array1, array2, array3))

      【讨论】:

        猜你喜欢
        • 2020-12-22
        • 2021-09-18
        • 1970-01-01
        • 2011-05-15
        • 1970-01-01
        • 2010-12-23
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        相关资源
        最近更新 更多