0

I have an array of languages as array=["en-ca", "fr-ca", "es-us", "en-us", "es-mx" ...etc]. There are lot of languages similar which repeats based on the country code. I want a filter to group them and create an array which just show the first two characters. For example: I want to find all the english [en-ca,en-us,fr-ca,es-mx,es-us] and just show [en,fr,es]. I can extract the first two characters by using split(-)[0]. But, how to get rid of the remaining values.

1
  • @DavidsaysreinstateMonica I have extracted the array with languages.map(lang => lang.substring(0, 2)) which gives me an array with just first two characters as ["en","es","fr","en","es ..etc] Commented Mar 26, 2021 at 16:49

3 Answers 3

1
const array = [ "en-ca", "fr-ca", "es-us", "en-us", "es-mx" /*...etc*/ ]

// Removes the country, leaving en, es, pt, etc
const langArr = array.map(item => item.split('-')[0])

// Removes all the duplicates
const result = Array.from(new Set(langArr))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use filter() to get a new array with the filtered values: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

You can also use include() to check if the checked object contains the value you are looking for.

https://developer.mozilla.org/he/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Of course you can combine them if you wish to. Recommended flow - filter the array , and then split the values

Comments

0

My own suggestion would be:

// the original Array:
let array = ["en-ca", "fr-ca", "es-us", "en-us", "es-mx"],

  // here we use Array.prototype.reduce() to reduce the
  // Array to something else (without modifying the original
  // Array):
  groups = array.reduce(
    // we pass in the accumulator - the thing that
    // Array.prototype.reduce() will return - and
    // the current Array-element of the Array over
    // which we're iterating:
    (acc, curr) => {
    
      // using a destructuring assignment to set
      // the Array values returned after we split
      // the String - using String.prototype.split()
      // - to the named variables:
      let [key, val] = curr.split('-');
      
      // if there is no Object-property for the current
      // key
      if (!acc[key]) {
        // we assign that Object-property - using square
        // bracket notation - and initialise it to an Array:
        acc[key] = [];
      }
      
      // we then use Array.prototype.push to enter the current
      // value into the Array:
      acc[key].push(val);
      
      // returning the accumulator:
      return acc;
    
    // the {} is the accumulator we're passing into the
    // function:
    }, {});
<ul></ul>

Demo:

let array = ["en-ca", "fr-ca", "es-us", "en-us", "es-mx"],
  groups = array.reduce(
    (acc, curr) => {
      let [key, val] = curr.split('-');
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(val);
      return acc;
    }, {});

const logObjectToScreen = (objet) => {
  let D = document,
    ul = D.createElement('ul'),
    li = D.createElement('li'),
    span = D.createElement('span'),
    fragment = D.createDocumentFragment();

  Object.keys(objet).forEach(
    (key) => {
      let clone = li.cloneNode();
      clone.textContent = `${key}: `;
      objet[key].forEach(
        (name) => {
          let temp = span.cloneNode();
          temp.textContent = name;
          clone.append(temp);
        });
      fragment.append(clone);
    });

  ul.append(fragment);

  document.body.append(ul);

}

logObjectToScreen(groups);
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font-size: 1rem;
  line-height: 1.5;
  margin: 0;
  padding: 0;
}

ul,
li {
  list-style-type: none;
  margin-left: 0.5em;
}

span::before {
  content: '"';
}

span::after {
  content: '," ';
}

span:last-child::after {
  content: '." ';
}

JS Fiddle demo.

References:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.