I have an array with length 220 as follows:
var tF = ["PETMEI 2011: the 1st international workshop on pervasive eye tracking and mobile eye-based interaction","Pseudo-Volumetric 3D Display Solutions", .....]
I want to create an array like this:
var arr = ["PETMEI","2011:", "the", "1st", "international", "workshop".........]
I have tried this method but it doesn't work as intended:
var arr = Object.keys(tF).map(function(k) { return tF[k] });
Any ideas on how to create an array as fast as possible?
Here is my working DEMO.
Thanks for your help!
-
It's an array of strings; split each one on spaces, and gather it up however you need it?Dave Newton– Dave Newton2015年04月17日 14:49:07 +00:00Commented Apr 17, 2015 at 14:49
-
Just to point it out again: you don't have JSON and you don't have an object.Felix Kling– Felix Kling2015年04月17日 15:28:50 +00:00Commented Apr 17, 2015 at 15:28
6 Answers 6
It looks like a string so just .split it
var arr = tF[0].split(/\s/);
If you want all of tF flattened into one big array,
var arr = [];
tF.forEach(function (e) {arr = arr.concat(e.split(/\s/));});
2 Comments
tF[0].split(/\s/).filter(Boolean); will remove the extra empty array items that are blank (caused by double spaces).split(/\s+/) instead of two steps. I didn't write this as OP didn't define behaviour for such occurrences thoughYou could use map followed by concat:
var arr = tF.map(function(k) {
return k.split(' ')
});
arr = Array.prototype.concat.apply([], arr);
Example: http://jsfiddle.net/whtb9ves/2/
3 Comments
Object.keys(tF).map for an array? just tF.map would be better..keys in this particular caseThis is the shortest one.
var arr = tF.join(' ').split(/\s+/);
Comments
You could do like this:
var arr = tF.reduce(function(a, b) {
return a.concat(b.split(/\s+/));
}, []);
console.log(arr);
1 Comment
Maybe use array concat?
var tF = ["PETMEI 2011: the 1st international workshop on pervasive eye tracking and mobile eye-based interaction","Pseudo-Volumetric 3D Display Solutions"]
var newArr = [];
for(var key in tF)
{
newArr = newArr.concat(tF[key].split(' '));
}
console.log(newArr);
Comments
If I understand it correctly, what you need to do is "split" the string by " " to turn it into an array of words.
http://jsfiddle.net/whtb9ves/1/
var arr = Object.keys(tF).map(function(k) { return tF[k].split(" ") });
If you are looking at splitting by words - you might want to look at normalizing it too, such as removing punctuation etc. It does depend on the application...