Js newbie here.
I have the following array:
Array [
Array [
"Canadian",
"57",
],
Array [
"",
"Tire",
"64",
],
Array [
"",
"#",
"67",
],
Array [
"",
"168",
"68",
],
Array [
"",
"65",
"84",
],
Array [
"",
"Pinebush",
"84",
],
Array [
"",
"Road",
"86",
],
Array [
"",
",",
"87",
],
Array [
"",
"Cambridge",
"88",
],
Array [
"",
"ON",
"90",
],
Array [
"",
"Bruno",
"108",
],
Array [
"",
"R",
"109",
],
Array [
"",
",",
"109",
],
Array [
"",
"General",
"109",
],
Array [
"",
"Manager",
"110",
],
]
which I would like to turn into following array:
Array [
Array [
"Canadian Tire # 168",
"57 64 67 68",
],
Array [
"65 Pinebush Road , Cambridge ON",
"84 86 87 88 90",
],
Array [
"Bruno R , General Manager",
"108 109 109 109 110",
],
]
The values in nested arrays change from strings to numbers, punctuation marks and whitespace. But the last values in arrays are y-coordinates for each word position, ie:
"Canadian", <---word
"57", <----its y-coordinate
"",<--- empty string
"Tire",<---another word
"64",<---another y-coordiante
The goal is to group words according to their y-coordinates falling within a small range difference:
57 64 67 68 are all within difference of 11,
84 86 87 88 90 are all within difference of 6 or
108 109 109 109 110 are all within difference of 2.
How would one accomplish this in vanilla js?
much obliged!
How about this:
var originalArray=[["Canadian","57"],["","Tire","64"],["","#","67"],["","168","68"],["","65","84"],["","Pinebush","84"],["","Road","86"],["",",","87"],["","Cambridge","88"],["","ON","90"],["","Bruno","108"],["","R","109"],["",",","109"],["","General","109"],["","Manager","110"]];
var newArray=[];
for(var item of originalArray) {
var age=Number(item[item.length-1]);
var group=age<80?0:age<100?1:2;
if(newArray[group]==undefined) newArray[group]=[[],[]];
for(var j=0; j<item.length-1; j++) if(item[j]!="") newArray[group][0].push(item[j]);
newArray[group][1].push(item[item.length-1]);
}
for(var item of newArray) {
item[0]=item[0].join(" ");
item[1]=item[1].join(" ");
}
for(var item of newArray) console.log(item);
It's assuming last sub-item is the age you want to group by.
I've manually grouped by under 80, then by under 100, and then - by the rest. You can modify that (you didn't specify how to find groups...).
It's adding the values into sub-arrays, and joining to a string afterwards.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加