Check if array contains specific character

Asked

Viewed 236 times

3

I need to check if an array has a specific character (this: | ). If it does, that character should be deleted and the next word that would be after that character (which is actually an item separation) would be added to the next index. That is, the array cannot have in its contents the character mentioned above. If there is, delete it and add in the array the word that would be after that character.

The attached image reflects the problem. I need to resolve with javascript/jquery.Exemplo do Array com o caractere específico onde preciso eliminá-lo e adicionar o item "Corte Masculino" no próximo index, que seria no caso desse exemplo: 6.

3 answers

10


If you want to change only the original array without creating a new one, it is still compatible with all browsers, including IE 11 (a Arrow Function item => in the forEach has no support in IE 11, without taking the merits of the vnbrs):

var array = ["Escova|Corte Masculino", "Gel", "Cabelo|Corte Masculino", "Escova", "Gel", "Gel|Corte Masculino"];

for(var x=0; x<array.length; x++){
   var i = array[x];
   var idx = i.indexOf("|");
   if(~idx){
      array[x] = i.substr(idx+1);
      array.splice(x, 0, i.substr(0, idx));
   }
}

console.log(array);

  • Excellent! Thank you so much for your help!

  • Good answer. I’ve been thinking about how functionalists do it. I believe a map inserting arrays with arrays for multiple items, followed by a Flatten. I don’t know....

7

You can use a loop, combined with the Array.concat and a String.split to separate items with the pipe.

const arrayOriginal = ["Tomate", "Abacaxi", "Carne|Fritas"];
let novoArray = [];

arrayOriginal.forEach(item => {
  novoArray = novoArray.concat(item.split("|"));
});

The result is

["Tomate", "Abacaxi", "Carne", "Fritas"]
  • 2

    I liked the code, very simple and lean, but if there was a way to not have to create another array, I mean, just by changing the original, it would be Perfect. But still a good answer.

  • Thank you for your contribution to my learning @Sam and @vnbrs!

2

Fala Pessoal :)

Just by adding here a way to do with jquery, it also uses regular expression, but can help a lot in the task of not creating a new Array 0/

var teste = ['Escova|Corte Masculino','Gel','Cabelo|Corte Masculino']; // Array com os dados
teste = teste.toString().replace('|',',').split(','); 

the above code is using 3 jQuery functions.

  • toString() - converts the array into a string and separates the array positions by "comma" Example : 'Brush|Cut, Male,Gel,Hair|Men’s Cut'
  • .replace('|',',') - this function as the name already says Replaces one value by the other, ie, the first parameter by the second. In this case the "|" for ","
  • .split(',') - and finally the SPLIT function divides the String from the parameter passed, which in turn is ",".

In the end the step by step is :

  • Takes the array and converts to string (separating the positions with comma)
  • Replaces | (Pipes) by comma.
  • Convert the string to Array again by splitting it every time you find a comma.

The big problem with this solution is that it applies replace only to the first occurrence it encounters, i.e., if the array contains more than one element with | it will only replace the first. (boring right?)

But relax, that here comes the regular expression to help.

.replace(/\|/g,',')

Using the regular expression causes replace to replace all pipe character occurrences (|) inside the string.

If you do not have family with regular expression, follow a good material for study: I want to learn

Finally, the final result of the method is :

var teste = ['Escova|Corte Masculino','Gel','Cabelo|Barba']; // Array com os dados
teste = teste.toString().replace(/\|/g,',').split(','); 

I hope I’ve helped :)

  • You’ve really helped @Abner Simões! Thank you so much for your contribution and help me learn! =]

  • Good @André Albson, Hit man.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.