Home > Software engineering >  slice strings of an array in javascript
slice strings of an array in javascript

Time:11-23

i am getting below array.

Array [
  "מאי 2017",
  "יוני 2017",
  "ינואר 2018",
  "פברואר 2018",
  "מרץ 2018",
  "מאי 2018",
  "יוני 2018",
  "נובמבר 2019",
  "אוגוסט 2020",
  "נובמבר 2020",
  "דצמבר 2020",
  "ינואר 2021",
]

and i have an english month array.

const englishMonthArray = [
    "",
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ]

how can i match only months of above array with English months?Thanks

CodePudding user response:

  1. Create a dictionary object that maps the Hebrew month (key) to the English equivalent (value).

  2. map over the array. split the string on the space, get the English month from the dictionary, and then return a new string.

const arr=["מאי 2017","יוני 2017","ינואר 2018","פברואר 2018","מרץ 2018","מאי 2018","יוני 2018","נובמבר 2019","אוגוסט 2020","נובמבר 2020","דצמבר 2020","ינואר 2021"];

const dict = {
  ינואר: 'January',
  פברואר: 'February',
  מרץ: 'March',
  אַפּרִיל: 'April', 
  מאי: 'May',
  יוני: 'June',
  יולי: 'July',
  אוגוסט: 'August',
  יולי: 'September',
  יולי: 'October',
  נובמבר: 'November',
  דצמבר: 'December'
};

const out = arr.map(el => {

  // This was interesting. For an English string
  // this would be destructured like [year, month].
  // I'm assuming that because there's Hebrew in the string
  // JS/the browser reads it differently (right to left).
  const [ month, year ] = el.split(' ');
  const enMonth = dict[month];
  return `${year} ${enMonth}`;
});

console.log(out);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Related