简体   繁体   English

如何排序数组但在字符串中查找数字之前?

[英]How sort array but before find numbers in string?

I want to sort my items by Title.我想按标题对我的项目进行排序。 My title has a number and if I put default sorting my titles look like this: 1, 10, 11, 12, 2, 20, 21 Expect result 1, 2, 10, 11, 12, 20, 21我的标题有一个数字,如果我设置默认排序,我的标题如下所示:1、10、11、12、2、20、21 预期结果 1、2、10、11、12、20、21

Me title looks like E01 how to... , E02 how to... , E20 how to...我的标题看起来像E01 how to...E02 how to...E20 how to...

my code我的代码

export interface Tag extends StoryblokComponent<string> {
  text: string;
  color: string;
}

type PodcastContent = {
  heading: string;
  subHeading: string;
  tags: Tag[];
  fullSlug: string;
  image: StoryblokAsset;
  podcastSrc: string;
};

type PodcastsBlok = {
  heading: string;
  disableMarginTop: boolean;
  link: StoryblokSimpleLink;
  linkText: string;
  podcasts: (StoryData<PodcastContent> & { default_full_slug: string })[];
};

export type SerializePodcasts = (PodcastProps & {
  id: string;
  podcastSrc: string;
  publishedAt: Date;
})[];

export const serializePodcasts = (podcasts: PodcastsBlok["podcasts"]) =>
  podcasts
    .map((item) => {
      const isStory = typeof item === "object";
      if (isStory) {
        const {
          uuid,
          published_at,
          content: { tags, heading, image, subHeading, podcastSrc },
          default_full_slug,
        } = item;

        return {
          publishedAt: new Date(published_at as string),
          id: uuid,
          heading,
          subHeading,
          tags: tags.map(({ _uid, color, text }) => ({
            id: _uid,
            color,
            text,
          })),
          podcastSrc,
          image: storyblokImageToMetadata(image),
          fullSlug: default_full_slug,
        };
      }
      return null;
    })
    .filter(Boolean)
    .sort(
      // @ts-ignore
      (a,b) => (b.heading < a.heading ? -1 : 1)
    ) as SerializePodcasts;



export type { PodcastsBlok, PodcastContent };

As I understand I should find a number in a string and perform sorting based on the result.据我了解,我应该在字符串中找到一个数字并根据结果执行排序。 How do I do it with my code?我该如何使用我的代码?

Use regex to find a number inside the string使用正则表达式在字符串中查找数字

 const data = ['E01 how to...', 'E02 how to...', 'E20 how to...'] const sorted = data.sort((a, b) => { const aNumber = Number(a.match(/\d+/)) const bNumber = Number(b.match(/\d+/)) return aNumber - bNumber }) console.log(sorted)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM