Split array [0] element and filter, then put into new table

75 Views Asked by At

I try to split sentence to single words and then filter it deleting unwanted words. After that put new content into new table like on picture and jsfiddle demo.

The problem is:

  1. I cant split this (i tried .split(" "); )
  2. I have no idea how to make it works for every array (i tried ".map")

Please watch demo: https://jsfiddle.net/Ashayas/xetqznLb/

Screen: (dont be scary about colors, they show what i want to achieve) IMAGE - CONSOLE LOG

CODE:

// I try to go from arr to tab
arr = [];
arr[0] = ["1. XXX Be yourself; XXX everyone else YYY is XXX already taken."];
arr[1] = ["2. Dont cry ZZZ ZZZ because its over, smile ZZZ because it happened 50.50 30:30"];

tab = [];
tab[0] = ["1.", "Be", "yourself;", "everyone", "else", "is", "already", "taken."];
tab[1] = ["2.", "Dont", "cry", "because", "its", "over", "smile", "because", "it", "happened", "50.50", "30:30"];

var unwanted_content = ["XXX", "YYY", "ZZZ"];
2

There are 2 best solutions below

1
On BEST ANSWER

I am not sure of what is your expected answer. Meaning, what do you expect to store in tab You can use a combination of join, includes and split methods. You could try something like this

var splitCharacter = " ";
var originalContent = [
  ["1. XXX Be yourself; XXX everyone else YYY is XXX already taken.", "XXX another one"],
  ["2. Dont cry ZZZ ZZZ because its over, smile ZZZ because it happened 50.50 30:30"]
];
var unwantedContent = ["XXX", "YYY", "ZZZ"];

var tab = [];
for (var i = 0; i < originalContent.length; i++) {
  console.log("*********************************");
  tab[i] = originalContent[i].join(" ").split(splitCharacter);
  tab[i] = tab[i].filter(x => !unwantedContent.includes(x));
  console.log("Original and filtered contents: ");
  console.log(originalContent[i]);
  console.log(tab[i])
  console.log("_________________________________");
}

2
On

Assuming you have your array set like that, you could use regex to remove unwanted content

var unwanted_content = [/XXX/g, /YYY/g, /ZZZ/g];

var tab = [];
arr.forEach(function(array) {
  var string = array[0];
  unwanted_content.forEach(function(unwanted) {
    string = string.replace(unwanted, '');
  })
  string = string.replace(/ +/g, ' ');
  tab.push(string.split(' '));
})

The replace(/ +/g, ' ') is to remove duplicated white space, so your array stays the way you want it