Sort a Javascript array based on every other element -


assume have array so:

var = [94, "neptunium", 2, "helium", null, "hypotheticalium", 64, "promethium"]; 

even-numbered array indices linked following odd index. in other words, 94 goes "neputunium" , 2 goes "helium" etc. how can sort array based on even-numbered indices keep following odd-indexed value after it? end array so:

a = [null, "hypotheticalium", 2, "helium", 64, "promethium", 94, "neptunium"]; 

note: , yes, know know using object or es6 map (or even, in case, sparse array numbers indices, if null left out) more appropriate, i'm exploring experiment language. help.

since order of calls sort not same 1 javascript engine next (or between revs of same engine), can't use sort directly on array you've described.

you can use map, filter, sort, reduce however:

var = [94, "neptunium", 2, "helium", null, "hypotheticalium", 64, "promethium"];  =    .map(function(entry, index, array) {      return (index % 2 === 1) ? null : {        value: array[index + 1],        index: entry      };    })    .filter(function(entry) {      return entry != null;    })    .sort(function(left, right) {      return left.index - right.index; // works when either or both                                       // indexes null, provided                                       // no non-null index negative,                                       // because `null` coerce 0    })    .reduce(function(acc, entry) {      acc.push(entry.index, entry.value);      return acc;    }, []);  document.body.innerhtml = json.stringify(a);

the map lets produce array objects paired entries (and nulls).

the filter lets remove nulls.

the sort lets sort.

the reduce lets produce array of results (since can't use map directly map 1 entry two).

if may have negative values even-numbered entries, sort callback has handle things differently because sort null above negative indexes (unless of course that's want).


it's bit more concise in es6: (live on babel's repl)

let = [94, "neptunium", 2, "helium", null, "hypotheticalium", 64, "promethium"]; =   .map((entry, index, array) => {     return (index % 2 === 1) ? null : {       value: array[index + 1],       index: entry     };   })   .filter(entry => entry != null)   .sort((left, right) => left.index - right.index)   .reduce((acc, entry) => {     acc.push(entry.index, entry.value);     return acc;   }, []); console.log(a); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -