Wave sort in Javascript - javascript

I have written a function to perform wave-sort as shown below. The resulting array should begin with a number bigger than the next one but my code is not doing that. For example if the input is:
[73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]
...it gives an output of
[ 86, 96, 84, 85, 80, 82, 61, 73, 40, 56, 14, 36, 10 ]
instead of starting with a bigger number than the next, which is 96.
function waveSort(arr){
arr = arr.sort(function(a, b) {
return b - a;
});
for (var i = 1; i < arr.length; i += 2) {
if (arr[i-1] > arr[i]) {
var temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
}
if (i+1 < arr.length && arr[i+1] > arr[i]) {
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
return arr;
}

You have explicitly designed your function to start with a lower value.
In the first if you detect a situation where the first value is greater than the second, and if so, you swap them (when i = 1):
if (arr[i-1] > arr[i]) {
So it is normal you end up with a smaller value at index 0 than at index 1.
If you want your array to start with a "wave high", then change the conditions in your two ifs:
function waveSort(arr){
arr = arr.sort(function(a, b) {
return b - a;
});
for (var i = 1; i < arr.length; i += 2) {
if (arr[i-1] < arr[i]) {
var temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
}
if (i+1 < arr.length && arr[i+1] < arr[i]) {
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
return arr;
}
var waved = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(JSON.stringify(waved));

function waveSort(arr){
arr.sort((a,b)=>b-a);
for(var i=1;i<arr.length;i+=2){
var tmp = arr[i];
arr[i]=arr[i+1];
arr[i+1]=tmp;
}
return arr;
}
var wavesorted = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(wavesorted);

Another way would be to define a swap function and call it within the actual function like:
const swap = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]]);
const waveSort = (arr) => {
arr = arr.sort((a, b) => b - a);
for(let i = 1; i < arr.length; i += 2){
if(arr[i-1] < arr[i]) {
swap(arr, i-1, i)
}
if(i+1 < arr.length && arr[i+1] < arr[i]) {
swap(arr, i+1, i)
}
}
return arr;
}
var waved = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(JSON.stringify(waved));
`

Related

Add the elements of two dimensional array that have first element same [duplicate]

This question already has answers here:
A better way to group a multidimensional array
(1 answer)
Summing a 2D array by "group"
(2 answers)
Group and average array values based on index
(4 answers)
JavaScript sum multidimensional array element values
(6 answers)
Iterate over multi-dimensional array and return aggregated sum based on first index
(3 answers)
Closed 1 year ago.
I have following two dimensional array.
const arr = [
[56783, 43, 54, 64, 64],
[65424, 67, 56, 64, 22],
[56783, 45, 66, 23, 65]
];
I wanna add the values of internal array with the values of another internal array if both have first element same.
For above example arr[0][0] and arr[2][0] have the first element same, so the result should be like arr[56783, 88, 120, 87, 129]. Don't add the first element of internal array, for this example the first element is 56783. Thank you in advance.
You can try with
let arr = [
[56783, 43, 54, 64, 64],
[65424, 67, 56, 64, 22],
[56783, 45, 66, 23, 65]
];
for(let element in arr) {
let firstElement = arr[element];
for(let innerArrays in arr) {
if(arr[innerArrays][0] === firstElement[0] && element !== innerArrays){
for(let i = 1; i < firstElement.length; i++) {
firstElement[i] = firstElement[i]+arr[innerArrays][i]
}
//You can do this if you want to delete the element that is added to first
arr.splice(innerArrays, 1);
}
}
}
console.log(arr);
const arr = [
[56783, 43, 54, 64, 64],
[65424, 67, 56, 64, 22],
[56783, 45, 66, 23, 65]
];
function solve(arr) {
var m = {};
arr.forEach((ls) => {
var firstElement = ls[0];
if (!m[firstElement]) {
m[firstElement] = [];
}
m[firstElement] = mergeLists(ls, m[firstElement]);
});
var finalLs = [];
Object.keys(m).forEach((key) => {
finalLs.push(m[key])
});
return finalLs;
}
function mergeLists(a, b) {
if (a.length == 0)
return b;
if (b.length == 0)
return a;
var finalList = [a[0]];
for (var i = 1; i < a.length; i++) {
finalList.push(a[i] + b[i]);
}
return finalList;
}
console.log(solve(arr));
Solution:
const arrays = [
[56783, 43, 54, 64, 64],
[65424, 67, 56, 64, 22],
[56783, 45, 66, 23, 65]
];
// TODO: check if anything is undefined (would have to be done nearly everywhere)
// but thats not what you asked for
let result = [];
let same = [];
for (i in arrays) {
array = arrays[i]
for (j in arrays) {
if (j != i) {
innerarray = arrays[j]
if (array[0] == innerarray[0]) {
same.push([i, j]);
}
}
}
}
// TODO: check for duplicates => [ [ '0', '2' ], [ '2', '0' ] ]
// inside of same
r = 0;
for (p in same) {
partners = same[p];
temparrays = [];
for (o in partners) {
temparrays.push(arrays[partners[o]]);
}
temparray = [];
for (i in temparrays) {
array = temparrays[i];
for (j in array) {
if (j != 0) {
if (temparray[j] == undefined) {
temparray[j] = array[j];
} else {
temparray[j] = temparray[j] + array[j];
}
} else {
temparray[j] = array[j];
}
}
}
result[r] = temparray;
r++;
}
console.log(result);
Notes:
It has a very bad naming of varaibles and you should add declaration of varaibles (ex.: const, let) everywhere.
It is also not optimised in any way, and i think more complicated than necessary, but it does what you want.
BTW: i just took your text and converted it to code, you already explained what needed to be done.
My TODO:'s are there to give you hints how to evolve the code (without any optimizations taken into consideration).

switchMaxMin-Java Script

I have to write a function switchMaxMin(tab, n) that swaps the maximum element with the minimum element in an n-element array tab. We assume that all elements of the array are distinct (i. e. there are not a few maxima or minima). I don't know how to do this
I started to write the code and I came up with this:
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = tab[0];
var max = tab[0];
document.write("Tablica: ");
for (i = 1; i < tab.length; i++) {
document.write(tab[i] + ", ");
if (min > tab[i]) {
min = tab[i];
}
if (max < tab[i]) {
max = tab[i];
}
}
document.write("<br /><br />Max: " + max);
document.write("<br />Min: " + min);
To swap the elements you have also to store the indices of the max and min elements
if (min > tab[i]) {
min = tab[i];
minIndex = i;
}
if (max < tab[i]) {
max = tab[i];
maxIndex = i;
}
Then you can reassign it by a classical swap function
function swapper(maxInd, minInd) {
let temp = tab[maxInd];
tab[maxInd] = tab[minInd]
tab[minInd] = temp;
}
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = tab[0];
var max = tab[0];
var minIndex = 0;
var maxIndex = 0;
document.write("Tablica: ");
for (let i = 1; i < tab.length; i++) {
document.write(tab[i] + ", ");
if (min > tab[i]) {
min = tab[i];
minIndex = i;
}
if (max < tab[i]) {
max = tab[i];
maxIndex = i;
}
}
swapper(maxIndex, minIndex);
document.write("<br /><br />Max: " + max);
document.write("<br />Min: " + min);
document.write("<br /> After the swap " + tab.join(","));
function swapper(maxInd, minInd) {
let temp = tab[maxInd];
tab[maxInd] = tab[minInd]
tab[minInd] = temp;
}
Just another way to do it, slightly less efficient, but fewer lines of code.
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = Math.min.apply(null,tab);
var minIndex = tab.indexOf(min);
var max = Math.max.apply(null,tab);
var maxIndex = tab.indexOf(max);
var temp = tab[minIndex]
tab[minIndex] = tab[maxIndex]
tab[maxIndex] = temp;
console.log(tab)

How to get the numbers that appear a certain amount of times in an array

I should have asked in a simpler way without showing what I had been trying to do.
Supposing I have this array:
function scr(array, n){
}
scr([187,187,187,187,187,62,62,43,43,43,43,43,5,5,5], 5)
I would like to get an array that shows the numbers that appear a certain amount of times. In that case, I would like the numbers that appear 5 times and so give:
[187,43]
How can I do that, please?
PS: Sorry for the complicated previous question
You can use reduce to group items in an array, giving you a count of each number, and then filter it by the numbers with a count of 5:
const input = [187,187,187,187,187,62,62,43,43,43,43,43,5,5,5];
const count = input.reduce((a, num) => {
a[num] = (a[num] || 0) + 1;
return a;
}, {});
const fives = Object.entries(count)
.filter(([, occurrences]) => occurrences === 5)
.map(([num]) => Number(num));
console.log(fives);
Not the most performant but readable, its a good canidate for reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const numbers = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
function equalFive(array, num) {
return array.filter(i => i === num).length === 5;
}
function getNumbersThatAppearFiveTimes(array) {
return array.reduce((prev, curr) => {
if (!prev.includes(curr) && equalFive(array, curr)) {
return [...prev, curr]
}
return prev;
}, []);
}
console.log(getNumbersThatAppearFiveTimes(numbers))
This is a solution using lodash, which already have many of this functions built in so you your codebase can be cleaner.
const inputArray = [187,187,187,187,187,62,62,43,43,43,43,43,5,5,5];
const inputValue = 5;
const count = _.countBy(inputArray); // count each instance of values
const equality = _.pickBy(count, x => x === inputValue); // filter values with 5 appearances
const output = Object.keys(equality).map(Number); // convert to desired format
console.log(output); // [43, 187]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
var input_array = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
//Sort input array
input_array.sort();
var output_array = [];
var count = 0;
var current = input_array[0];
for(var i = 0; i < input_array.length; i++){
//Loop until change to next number
//Check if total quantity equals 5
if(input_array[i] != current){
//save into output if equals 5
if(count == 5){
output_array.push(current);
}
//reset counter
current = input_array[i];
count = 1;
}else{
count++;
}
}
console.log(output_array);
Using Array#reduce() to map counts into a Map object then Array#filter() to return results
function scr(array, n) {
const counts = array.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map);
return [...counts.keys()].filter(v => counts.get(v) >= n);
}
const input = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
console.log(scr(input, 5))
You could take a counter and filter the nth element of counting with a single loop.
function scr(array, n) {
var count = Object.create(null);
return array.filter(v => (count[v] = (count[v] || 0) + 1) === n);
}
console.log(scr([187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5], 5));

How to add array into a matrix in javascript?

I just want to know how can i add
var arr_bck = [];
for (var i = 0; i < rows_bck.length; i++) {
var sum = 0;
for (var j = 1; j < rows_bck[i].length; j++) {
if (rows_bck[i][j] == null) {
rows_bck[i][j] = 0;
sum += rows_bck[i][j];
} else {
sum += rows_bck[i][j];
}
}
arr_bck.push(sum);
}
into:
var rows_bck = _.chain(newarrAots).groupBy(function (item) { return item.date; }).map(function (group, key) {
var result = [key];
_.each(group, function (item) {
result[_.indexOf(header, item.teamName, arr_bck)] = item.aots_bck_cnt;
});
return result;
}).value();
i mean add arr_bck as new value in rows_bck matrix. Values in matrix are like this:
"02/11", 0, 0, 0, 0
"02/12", 193, 233, 212, 307
"02/13", 203, 264, 293, 227
and i want values like:
"02/11", 0, 0, 0, 0, 0
"02/12", 193, 233, 212, 307, 945
"02/13", 203, 264, 293, 227, 987
last values are sum of the int numbers in each row.
I guess this is what you need according to your question.
Just check the output of the snippet by running it :p
var rows_bck=
[
["02/11", 0, 0, 0, 0],
["02/12", 193, 233, 212, 307],
["02/13", 203, 264, 293, 227],
];
var arr_bck = [];
for (var i = 0; i < rows_bck.length; i++) {
var sum = 0;
for (var j = 1; j < rows_bck[i].length; j++) {
if (rows_bck[i][j] == null) {
rows_bck[i][j] = 0;
sum += rows_bck[i][j];
} else {
if(typeof(rows_bck[i][j]) === "number")
sum += rows_bck[i][j];
}
}
rows_bck[i].push(sum);
}
console.log(rows_bck)
const rows_bck=
[
["02/11", 0, 0, 0, 0],
["02/12", 193, 233, 212, 307],
["02/13", 203, 264, 293, 227]
];
const result = rows_bck.map(row => [...row, row.slice(1).reduce((sum,i)=> sum + i,0)]);
Explain:
.map(): We are mapping old rows to newer rows;
Spread ... operator to dump old elements in new row;
Use slice(1) to get all numbers by ignoring first element;
use reduce() to get the sum of the above numbers.

How to convert hex string into a bytes array, and a bytes array in the hex string?

The following code procedure bytes = parseHexString (createHexString (bytes)) leads to updated of bytes, what I would like to avoid. And as a result calculations are not correct.
<html>
<head>
<SCRIPT SRC="http://eu.static.mega.co.nz/sjcl_1.js"></SCRIPT>
<SCRIPT SRC="http://eu.static.mega.co.nz/crypto_1.js"></SCRIPT>
<SCRIPT SRC="http://eu.static.mega.co.nz/rsa_1.js"></SCRIPT>
<SCRIPT SRC="http://eu.static.mega.co.nz/hex_1.js"></SCRIPT>
<SCRIPT>
function parseHexString(str) {
var result = [];
while (str.length >= 2) {
result.push(parseInt(str.substring(0, 2), 16));
str = str.substring(2, str.length);
}
return result;
}
function createHexString(arr) {
var result = "";
for (i in arr) {
var str = arr[i].toString(16);
str = str.length == 0 ? "00" :
str.length == 1 ? "0" + str :
str.length == 2 ? str :
str.substring(str.length-2, str.length);
result += str;
}
return result;
}
function t()
{
var json_k = 'aOrP5yLtNQT53WMQfufSlA';
var json_csid = 'CABD6JUMldvI_eqP0537xl9P8x7kgk2OjOq99Fy7kosphj6AFUtlbwRRDpg4EIifXRLO6FNpdD22WwtUlJ_1Mgye2Y87trEqLCbhahuEFJVQNMDtNbIem7xY2ER9uF-cdgBXZWuzp7XIBybSh7W8MSUlv_eGS6LcLGJ81Q49dSzVhcswHTJ_IJl04p3c0axR6ZIJ8dH5bJ_vXvgQsypUVVtdfMacKhB9cXdEtRZ6iWLKCKqscXdo6CNXlbIdzRhro0gxfmhfB_miysFAiSQrbtuYnIgYBU3i9p3jRlPD4ti3CUcnj0SomV61w1aEYNvo56HPMUZlVkVHA7BFzvHGHo0J';
var json_privk = 'K7LDtk2M2QhjJx_v_Hqf0LKUBaZx76U_vBDjQty9HpFDy2MntF5HxxuyHQ9-1HmXeYzbL1pZnAxsZ7LRUbDnkR6qtJVaGdWuQhrytkuq0l5zBp-O--gZxoQPRGTsVgVRdAvpsRTkQI_q8fxADLCe0womFxtvvnD_FJgjaMsm7vkYchXkoq33WWyHijb3JMkymjl0_GtiSamT0qEL6sm_l5Z1lehqBGUEHfYAa0ub8IDx_yqy2R9Nh8Lwzmz4s24sShVxjaNsMBlSE-sEvTziOsnNWK1Zl_XUYadlENkweuIoxYx_lt8XIV71TzjEFuVTd-pXhzVlqePmIu3SM3bO1Kzq_DnGfB62RmzlmbtHU4iyw4Hd1wQFRhTeSRrvMjsMPFKN-SIIQU7CRNaMuaDxZbNZcOKhMg_h9mApM0rRS3VZaGZzFTL9rSaDMYHw4pL3aOkSFPMY3w785Tss7Zqwuo9HFUWUVbnYAb97JkgCohlMotORrMMtual1dQ4sG1sIYXyWTckAGGL0ZAGurhtSKiyz1m8Lb39pXPacqFh_nCHqqb2_RdrKTj0PdGZESKkU8YedeqC1I9nR4v38DuQc-pBBR5DOwgNjJMvzvsUehs_PxIL8THjgIcr7ONc4hWV9o2v_l81Vo2cCW2I99Iz84IFN2fV1dTqHIG_tnLzz8ljBVygETUqrFdZ0JlQJkurZ7RBku5krm-k9CZmDezCIzPPil-RcYzVIk00gNYAxfiZE48Or4WEiGjgKLnHCYVtSlvlMF4bPGB4SVCZ-68j49EjfSWaMK0OoMkpGhqf7KchgxYBZq6o3AhLgp4t0BClvsdee6VTz1SFqc3m2A-TMG6fNdbCT_Q9nYCYdZIROdOc';
var aes = new sjcl.cipher.aes( prepare_key_pw("oEyoo9cQcw") );
k = decrypt_key(aes, base64_to_a32(json_k) );
aes = new sjcl.cipher.aes(k);
var t = mpi2b(base64urldecode(json_csid));
var privk = a32_to_str(decrypt_key(aes,base64_to_a32(json_privk)));
var rsa_privk = Array(4);
for (var i = 0; i < 4; i++)
{
var l = ((privk.charCodeAt(0)*256+privk.charCodeAt(1)+7)>>3)+2;
rsa_privk[i] = mpi2b(privk.substr(0,l));
if (typeof rsa_privk[i] == 'number') break;
privk = privk.substr(l);
}
var p = parseHexString(createHexString(rsa_privk[0])); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!
var q = parseHexString(createHexString(rsa_privk[1])); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!
var d = parseHexString(createHexString(rsa_privk[2])); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!
var u = parseHexString(createHexString(rsa_privk[3])); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!
sid = base64urlencode(b2s(RSAdecrypt(t,d,p,q,u)).substr(0,43));
if (sid!=='tajetAbW0qTQGFlwp8iD5lQ0TFV1QUZJZFVvjRX7Xx-bPzYBoau7qog09w')
console.log("ERROR");
p = rsa_privk[0];
q = rsa_privk[1];
d = rsa_privk[2];
u = rsa_privk[3];
sid = base64urlencode(b2s(RSAdecrypt(t,d,p,q,u)).substr(0,43));
if (sid=='tajetAbW0qTQGFlwp8iD5lQ0TFV1QUZJZFVvjRX7Xx-bPzYBoau7qog09w')
console.log("OK");
}
</script>
</head>
<body onload="t();"></body>
</html>
I am not javascript developer, and not one found in google code did not work on this data.
Update 1
console.log(createHexString(rsa_privk[0])); = e5d109c673d8ef03df564beb9e36e9983a23842b0a724efa45ff76bbe5ad72ed62d2757968
But if do
parseHexString('e5d109c673d8ef03df564beb9e36e9983a23842b0a724efa45ff76bbe5ad72ed‌​62d2757968');
then code if (sid!== ... make error
Update 2
console.log(rsa_privk[0].toString(16));
output:
123676133,198914513,129998601,245147334,11918451,206998232,96766191,75984899,177840095,106709334,10180427,208237547,119814814,127003446,189062377,84099480,220452154,250519075,267883908,115471915,165124106,238628722,169382478,42320122,95982405,80725759,89608310,85166267,200925925,254033325,86971506,191278317,127411298,180195794,142776693,188738169,39016
Update 3
console.log(parseHexString(createHexString(rsa_privk[0])));
console.log(rsa_privk[0]);
output:
[229, 209, 9, 198, 115, 216, 239, 3, 223, 86, 75, 235, 158, 54, 233, 152, 58, 35, 132, 43, 10, 114, 78, 250, 69, 255, 118, 187, 229, 173, 114, 237, 98, 210, 117, 121, 104]
[123676133, 198914513, 129998601, 245147334, 11918451, 206998232, 96766191, 75984899, 177840095, 106709334, 10180427, 208237547, 119814814, 127003446, 189062377, 84099480, 220452154, 250519075, 267883908, 115471915, 165124106, 238628722, 169382478, 42320122, 95982405, 80725759, 89608310, 85166267, 200925925, 254033325, 86971506, 191278317, 127411298, 180195794, 142776693, 188738169, 39016]
Convert a hex string to a byte array and vice versa
note: implementation from crypto-js, though now out of date and slightly altered
// Convert a hex string to a byte array
function hexToBytes(hex) {
let bytes = [];
for (let c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
// Convert a byte array to a hex string
function bytesToHex(bytes) {
let hex = [];
for (let i = 0; i < bytes.length; i++) {
let current = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
hex.push((current >>> 4).toString(16));
hex.push((current & 0xF).toString(16));
}
return hex.join("");
}
Update: Scroll down for solution... Live Demo
The issue: you are using a lossy conversion to hex, which cannot be reversed.
var p = parseHexString(createHexString(rsa_privk[0]));
This will never be same as rsa_privk[0].
Because, createHexString() only uses the last 2 bytes from each array element.
Example:
rsa_privk[0] : [123676133, 198914513, 129998601, 245147334, 11918451, 206998232, 96766191, 75984899, 177840095, 106709334, 10180427, 208237547, 119814814, 127003446, 189062377, 84099480, 220452154, 250519075, 267883908, 115471915, 165124106, 238628722, 169382478, 42320122, 95982405, 80725759, 89608310, 85166267, 200925925, 254033325, 86971506, 191278317, 127411298, 180195794, 142776693, 188738169, 39016]
createHexString(rsa_privk[0]) : e5d109c673d8ef03df564beb9e36e9983a23842b0a724efa45ff76bbe5ad72ed62d2757968
parseHexString(createHexString(rsa_privk[0])) : [229, 209, 9, 198, 115, 216, 239, 3, 223, 86, 75, 235, 158, 54, 233, 152, 58, 35, 132, 43, 10, 114, 78, 250, 69, 255, 118, 187, 229, 173, 114, 237, 98, 210, 117, 121, 104]
Update : Working Solution...
The two functions... the hex always contains 8 byte blocks, each for each element in the array...
function parseHexString(str) {
var result = [];
while (str.length >= 8) {
result.push(parseInt(str.substring(0, 8), 16));
str = str.substring(8, str.length);
}
return result;
}
function createHexString(arr) {
var result = "";
var z;
for (var i = 0; i < arr.length; i++) {
var str = arr[i].toString(16);
z = 8 - str.length + 1;
str = Array(z).join("0") + str;
result += str;
}
return result;
}
Test code...
function test() {
a = [123676133, 198914513, 129998601, 245147334, 11918451, 206998232, 96766191, 75984899, 177840095, 106709334, 10180427, 208237547, 119814814, 127003446, 189062377, 84099480, 220452154, 250519075, 267883908, 115471915, 165124106, 238628722, 169382478, 42320122, 95982405, 80725759, 89608310, 85166267, 200925925, 254033325, 86971506, 191278317, 127411298, 180195794, 142776693, 188738169, 39016];
console.log("Input");
console.log(a);
b = createHexString(a);
console.log("Hex");
console.log(b);
c = parseHexString(b);
console.log("Output");
console.log(c);
if(checkIfEqual(a, c)) {
alert("Same");
}
}
function checkIfEqual(arr1, arr2) {
if (arr1.length != arr2.length) {
return false;
}
//sort them first, then join them and just compare the strings
return arr1.sort().join() == arr2.sort().join();
}
I just wanted to chime in that there is a library at https://github.com/dcodeIO/bytebuffer.js to easily help with conversions like this, and thus you don't need to write your own functions (which could possibly not be the most optimal, or be more optimal if your solution was reviewed through the open source community on GitHub).
var ByteBuffer = require("bytebuffer");
var bb = ByteBuffer.fromHex(yourHexString);
// need to convert it to base 64?
// bb.toBase64();
See https://github.com/dcodeIO/bytebuffer.js/wiki/API#bytebufferfromhexstr-littleendian-noassert for the API documention and more insight on the methods I used above.
Just to clarify, if you simply want to hex decode a simple string such as 48656C6C6F20576F726C6421 (Hello World!) you can use the OP function but instead of using a length of 8 you should use a length of 2.
Code:
var DecodeHexStringToByteArray = function (hexString) {
var result = [];
while (hexString.length >= 2) {
result.push(parseInt(hexString.substring(0, 2), 16));
hexString = hexString.substring(2, hexString.length);
}
return result;
}
Output will be [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
I know that this code is already in the OP question, but it's not in the accepted answer. My intent here is only to give a straight answer to the first part of the question being asked (How to convert a hex string into a bytes array).
I found solution over here enter link description here
function hexStringToByteArray(hexString) {
if (hexString.length % 2 !== 0) {
throw "Must have an even number of hex digits to convert to bytes";
}
var numBytes = hexString.length / 2;
var byteArray = new Uint8Array(numBytes);
for (var i=0; i<numBytes; i++) {
byteArray[i] = parseInt(hexString.substr(i*2, 2), 16);
}
return byteArray;
}
once again thank you http://www.java2s.com
Here is a live sample for this test.
http://jsfiddle.net/vincentwang2020/eks1z4g2/
function testcreateHexString()
{
alert('test function createHexString');
var key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
var result = createHexString(key);
alert ('Hex value:' + result);
alert('test function parseHexString');
var key2 = parseHexString(result);
if (key.sort().join() == key2.sort().join())
alert ('Matched');
}

Categories