skip to Main Content

I’m trying to turn this array into 2 different arrays. One array should be of names that contain the letter ‘o’ in them and the second array should be the rest of the names, that do not have ‘o’.

Given array:

var names = ['octavia', 'peter', 'olive', 'ava', 'aiden']; 

Desire result:

var nameO = ['octavia', 'olive'];
var nameNoO = ['peter', 'ava', 'aiden'];

This is the code I came up with. Got one of the results for names with ‘o’, but not without ‘o’.

var names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
var namesO = [];
var namesNoO = [];
for(let i in names){
  for(let j in names[i]){
    if(names[i][j] === 'o'){
      namesO.push(names[i]);
    } 
    if(names[i][j] !== 'o'){
    namesNoO.push(names[i])
    }
 }
}
console.log(namesO, namesNoO); 

5

Answers


  1. You can use the .filter function of an array to filter the items. For each string, you can use .includes to check if it includes the letter "o". The .toLowerCase function converts the input strings to lowercase before comparing them, making sure this works for both capital and lowercase letters.

    var names = ['John', 'Alice', 'Bob', 'Carol', 'Oliver', 'Sophia'];
    
    var namesWithO = names.filter(name => name.toLowerCase().includes('o'));
    var namesWithoutO = names.filter(name => !name.toLowerCase().includes('o'));
    

    Or

    names.forEach(name =>
    {
       if (name.includes('o'))
       {
          namesWithO.push(name);
       }
       else
       {
          namesWithoutO.push(name);
       }
    });
    
    Login or Signup to reply.
  2. When iterating over characters of names, if a name has ‘o’ in it, you’re pushing the name into namesO array multiple times based on the number of characters in the name, which is incorrect. Similarly, if a name doesn’t have an ‘o’, it will be pushed into namesNoO multiple times because of the inner loop.

    var names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
    var namesO = [];
    var namesNoO = [];
    
    for(let i = 0; i < names.length; i++){
        if(names[i].startsWith('o')){
            namesO.push(names[i]);
        } else {
            namesNoO.push(names[i]);
        }
    }
    
    console.log(namesO, namesNoO); 
    
    Login or Signup to reply.
  3. You should spend some time familiarizing yourself with all of the various functions that are part of the Array prototype.

    Saying you want to "split" an array suggests you are looking for Array.prototype.slice(). However, your example suggests what you really want to do is filter your array. To do that you want to use the Array.prototype.filter() function.

    const names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
    const withNoO = name => !name.includes('o');
    const withO = name => name.includes('o');
    
    const nameO = names.filter(withO);
    // ['octavia', 'olive'];
    
    const nameNoO = names.filter(withNoO)
    // ['peter', 'ava', 'aiden'];
    

    I am using "arrow functions" to make the code more compact. This could also be done like this:

    function withNoO(name) {
        return !name.includes('o');
    }
    
    function withO(name) {
        return name.includes('o');
    }
    
    const nameO = names.filter(withO);
    // ['octavia', 'olive'];
    
    const nameNoO = names.filter(withNoO)
    // ['peter', 'ava', 'aiden'];
    
    Login or Signup to reply.
  4. You can use include for condition matching.

       var names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
       var namesO = [];
       var namesNoO = [];
    
      for(var i=0, l = names.length; i < l; i++) {
         if(names[i].toLowerCase().includes("o")){
          namesO.push(names[i]);
          }
      if(!names[i].toLowerCase().includes("o")){
          namesNoO.push(names[i]);
        }
        }
         console.log(namesO,namesNoO);
    
    Login or Signup to reply.
  5. You can reduce the array with 2 arrays as the accumulator ( O(n) ).
    +name.includes('o') gives you an index of 2 arrays to push the names to:

    const names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
    
    const [withoutO, withO] = names.reduce((r, name) => (r[+name.includes('o')].push(name) , r), [[], []]);
    
    console.log(withO, withoutO);
    ` Chrome/117
    ----------------------------------------------------------------
    Alexander            1.0x  |  x10000000  447  451  463  470  483
    Mister Jojo          1.7x  |  x10000000  753  757  758  764  779
    Damian Chudobiński   2.5x  |   x1000000  111  114  115  115  124
    Jordy                2.9x  |   x1000000  129  129  131  133  133
    ----------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    const names = ['octavia', 'peter', 'olive', 'ava', 'aiden'];
    
    // @benchmark Jordy
       var namesO = [];
       var namesNoO = [];
    
      for(var i=0, l = names.length; i < l; i++) {
     if(names[i].toLowerCase().includes("o")){
      namesO.push(names[i]);
      }
      if(!names[i].toLowerCase().includes("o")){
      namesNoO.push(names[i]);
    }
    }
    [namesO,namesNoO];
    
    // @benchmark Damian Chudobiński
    
    [names.filter(name => name.toLowerCase().includes('o')),
    names.filter(name => !name.toLowerCase().includes('o'))];
    
    // @benchmark Mister Jojo
    names.reduce((r,n)=>(r[(/o/i.test(n)?0:1)].push(n),r),[[],[]])
    
    // @benchmark Alexander
    names.reduce((r, name) => (r[+name.includes('o')].push(name) , r), [[], []]);
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search