简体   繁体   中英

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

Me title looks like 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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