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
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.Or
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.
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 theArray.prototype.filter()
function.I am using "arrow functions" to make the code more compact. This could also be done like this:
You can use include for condition matching.
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: