【问题标题】:Placing an element in the same index as element in an array将元素放置在与数组中的元素相同的索引中
【发布时间】:2021-08-13 10:47:30
【问题描述】:

我正在尝试找出获取元素的最佳方法,将其与现有数组中的元素进行比较,如果返回 true,则将该元素推送到具有相同索引的另一个数组中。

我目前有一个数组,但它需要以特定的顺序出现,所以我所做的是创建一个数组,其顺序是它需要的顺序。我考虑创建一个对象,其中键的每个值都是数组并将元素推送到数组中,等于键,但不确定这是否是最好的方法。

这是我目前正在使用的代码:

let categories = [];
  const categoryOrder = [
    "Headings",
    "Text",
    "Lists & Menus",
    "Quotes",
    "Banners",
    "Images",
    "Videos",
    "Galleries",
    "Logos",
    "Clickthrough Images",
    "Buttons & CTAs",
    "Lines & Dividers",
    "Actions",
    "Social Media & Integrations",
    "Blog, Events & Podcast",
    "Ecommerce",
    "Navigation",
    "Footers",
    "Premium",
    "Misc",
  ];

  defaultComponents &&
    defaultComponents.forEach((component) => {
      categories.push(component.category);
    });
  categories = [...new Set(categories)];

希望这是有道理的。

【问题讨论】:

    标签: javascript arrays sorting


    【解决方案1】:

    Array.map 允许您通过转换每个元素将现有数组映射到另一个数组

    const newArray = originalArray.map(value => {
      if (condition(value)) {
         return newValue
      }
    })
    

    索引将被保留,当条件不真实时,您将获得未定义的值

    【讨论】:

    • 对于数组中元素的索引是否仍然有效?
    【解决方案2】:

    如果defaultComponents 中存在的数据还没有您想要的顺序,或者您只获得categoryOrder 数组具有的类别的子集,那么您可以执行以下操作:

    const categories = defaultComponents.map((c) => c.category);
    categories.sort((a, b) => {
      const aIndex = categoryOrder.indexOf(a);
      const bIndex = categoryOrder.indexOf(b);
      return aIndex === bIndex ? 0 : aIndex < bIndex ? -1 : 1;
    });
    

    【讨论】:

    • 感谢 Octavian,这有助于解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多