Convert buffer to array - javascript

I am setting memcached with
$memcached->set("item" , ["1" => "hello"]);
anything work in PHP ,
In Node.js with memcached plugin , I get a buffer instead of array in result
<Buffer 61 3a 25 61 34 3a>
I can not convert such buffer to array
In Node.js :
memcached.get("item" , function(err, data) {
console.log(data);
}
Do you have any way ?

arr = [...buffer]
ES6 introduced a lot of other features, besides buffers.
You can even easily append like this:
arr.push(...buffer)
The ... operator expands enumerables such as arrays and buffers when used in array. It also expands them into separate function arguments.
Yes, it's also faster:
... : x100000: 835.850ms
Slice call from prototype : x100000: 2118.513ms
var array,
buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]),
iter = 100000;
array = buffer;
console.time("... : x" + iter);
for (var i = iter; i--;) array = [...buffer]
console.timeEnd("... : x" + iter);
console.time("Apply/call/etc : x" + iter);
for (var i = iter; i--;) array = Array.prototype.slice.call(buffer, 0)
console.timeEnd("Apply/call/etc : x" + iter);

There is another way to convert to array of integers
Using toJSON()
Buffer.from('Text of example').toJSON()
{ type: 'Buffer',data: [ 84, 101, 120, 116, 32, 111, 102, 32, 101, 120, 97, 109, 112, 108, 101 ] }
// simple get data
Buffer.from('Text of example').toJSON().data
[ 84, 101, 120, 116, 32, 111, 102, 32, 101, 120, 97, 109, 112, 108, 101 ]
Example of benchmark
// I took this from #user4584267's answer
const buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]);
let array = null;
const iterations = 100000;
console.time("...buffer");
for (let i = iterations; i=i-1;) array = [...buffer]
console.timeEnd("...buffer");
console.time("array.prototype.slice.call");
for (let i = iterations; i=i-1;) array = Array.prototype.slice.call(buffer, 0)
console.timeEnd("array.prototype.slice.call");
console.time("toJSON().data");
for (let i = iterations; i=i-1;) array = buffer.toJSON().data
console.timeEnd("toJSON().data");
OUTPUT
...buffer: 559.932ms
array.prototype.slice.call: 1176.535ms
toJSON().data: 30.571ms
or if you want more profesional and custom function in Buffer use this:
Buffer.prototype.toArrayInteger = function(){
if (this.length > 0) {
const data = new Array(this.length);
for (let i = 0; i < this.length; i=i+1)
data[i] = this[i];
return data;
}
return [];
}
Example of benchmark:
const buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]);
let array = null;
const iterations = 100000;
console.time("toArrayInteger");
for (let i = iterations; i=i-1;) buffer.toArrayInteger();
console.timeEnd("toArrayInteger");
Ouput:
toArrayInteger: 28.714ms
Note: In the last example I copied a function from Buffer.toJSON and custom it a lite

Here you go:
var buffer = new Buffer([1,2,3])
var arr = Array.prototype.slice.call(buffer, 0)
console.log(arr)

I haven't used memcached so I am not sure just what this buffer represents or what you want to have instead. Sorry. Here is a function to split a buffer up into an array of bytes. More at node.js Buffer docs, hope it helps!
var hex = new Buffer("613a2561343a", "hex");
var l = hex.length; // in bytes
var output = [];
for(var i = 0; i < l; i++){
var char = hex.toString('hex',i,i+1); // i is byte index of hex
output.push(char);
};
console.log(output);
// output: [ '61', '3a', '25', '61', '34', '3a' ]

You can also use Array.from:
memcached.get("item" , function(err, data) {
console.log(Array.from(data));
}

I have a solution, although I am currently trying to find a better one:
function bufToArray(buffer) {
let array = new Array();
for (data of buffer.values()) array.push(data);
return array;
}
EDIT : I found a simpler way:
var buffer = Buffer.from('NodeJS rocks!')
var array = new Function(`return [${Array.prototype.slice.call(buffer, 0)}]`)
But, like someone already said, [...buffer] is faster (and more code efficient).
You can also use new Uint8Array(buffer [, byteOffset [, length]]);

In interent , there was no information about that , but I have found the convert way
In nodejs , I have to use :
var arrayobject = phpjs.unserialize(data.toString());
but , it is very stupid way for getting array , it seem that php serilzie the data when setting memcache .

Related

Print all even values in all object key end with odd value

I want to print all even values in all object key end with odd value but the coding I made just now is only specified for arr1, arr3, and arr5. Can anyone suggest me how to fix 'let oddArr' method (maybe in loop) so that when I changed arr1 into arr7, the result would be the same.
var num = {
arr1 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
arr2 : [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
arr3 : [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
arr4 : [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
arr5 : [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
};
let oddArr = [...num.arr1, ...num.arr3, ...num.arr5] //need some correction here
let evenNum = oddArr.filter(number => number % 2 == 0);
console.log(evenNum.toString());
//help me fix 'let oddArr' (maybe in loop method) so that when I changed the object of the array (e.g: arr1 -> arr7) it would come out with the same result
//the result/output should be 2,4,6,8,10,22,24,26,28,30,42,44,46,48,50 based on var num
You can try like below using for in loop and it works with any last character as odd.
var num = {
arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
arr7: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
};
let oddArr = [];
for (let key in num) {
if (key.charAt(key.length - 1) % 2 !== 0) {
oddArr = [...oddArr, ...num[key]];
}
}
let evenNum = oddArr.filter((number) => number % 2 === 0);
console.log(evenNum.toString());
You might want to use
let oddArr = Object.entries(num).filter( // filter key names
e => +e[0].replace("arr", '') % 2 !== 0 // replace "arr" and check if X in arrX is odd
).map(e => e[1]).flat() // merge values and flattern array
You can also make use of regex if the "arrX"-naming is not consistent:
+e[0].match(/\d+/) % 2 !== 0
See a working snippet below:
var num = {
arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
arr5: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
};
let oddArr = Object.entries(num).filter(
e => +e[0].replace("arr", '') % 2 !== 0
).map(e => e[1]).flat()
let evenNum = oddArr.filter(number => number % 2 == 0);
console.log(evenNum.toString());
This also works.
var num = {
arr1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
arr2: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
arr3: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
arr4: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
arr5: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
arr6: [51, 52, 53, 55, 55, 56, 57, 58, 59, 60],
arr7: [61, 62, 63, 66, 65, 66, 67, 68, 69, 70],
};
var evenNums = Object.keys(num).filter((item) => {
itemNum = item.replace("arr", "");
return itemNum % 2 !== 0;
}).map((o) => num[o]).flat().filter((x) => x % 2 == 0);
console.log(evenNums);

forEach() method - looping over an array

I am totally new to coding so my question is probably very basic. I want to loop over the following array and every time the number is divisible by 3 I want to add 100. If not, just print the number. I want to do that with the forEach() method. This is my code but when I want to print it it says "undefined" What am I doing wrong?
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139];
test.forEach(function(num){
if(num %3 === 0){
return num+=100;
}else{
return num;
}
console.log(num) ;
})
Get rid of the return statements:
The return statement ends function execution and specifies a value to
be returned to the function caller.
Therefore it will never make it to the console.log line (this is what they call unreachable code since there is no possible path to it):
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139
];
test.forEach(function(num) {
if (num % 3 === 0) {
num += 100;
}
console.log(num);
})
I removed the else block because, as pointed out in the comments below, there is no purpose for it.
The approach above is fine if all you want to do is log the result, but if you want to get a new array that has stored all the new values then you should consider using Array.prototype.map like this:
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139
];
var updatedValues = test.map(num => num % 3 === 0 ? num + 100 : num);
console.log(updatedValues);
The problem is that the return keyword immediately stops the function, so you don't progress further. And since Array#forEach itself doesn't return anything, the keyword is pretty useless. You can just remove it and you'd get the behaviour you want:
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139];
test.forEach(function(num){
if(num %3 === 0){
num+=100;
}
console.log(num) ;
})
If you instead want to create a new array from the first one using the rules you've described, then you can simply substitute .forEach for the Array#map method:
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139];
var result = test.map(function(num){
if(num %3 === 0){
return num+=100;
}else{
return num;
}
})
console.log(result);
You should use map instead of forEach here since map will execute the provided function to each array item and return a new array.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Source
Just changing your current code, it can be like this
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139];
var result = test.map(function(num) {
if (num %3 === 0) {
return num + 100;
} else {
return num;
}
})
Or, you can also improve it further by separating things
const add100IfDividableBy3 = function (num) {
return (num % 3 === 0) ? num + 100 : num;
}
const test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139];
const result = test.map(add100IfDividableBy3)
The function add100IfDividableBy3 uses what is called as a Ternary Operator

How to find the Minimum number of swaps required for sorting an array of numbers in descending order in javascript

I'm trying to get my code to do this:
Original array = [1,2,3,4] swap once-> [4,2,3,1] swap again->[4,3,2,1]
Therefore result is 2
But it's not working. Here's what I have so far:
function check(arr){
var sarr = [];
var cnt = 0;
var arrL = arr.length;
// Create a second copy of the array for reference
var arrCopy = [...arr];
for(let i=0; i<arrL;i++){
var maxV = Math.max(...arr);
sarr.push(maxV);
let pos = arr.indexOf(maxV);
// Remove the found number
arr.splice(pos,1);
// Check if the index of the number in the new array is same with the copy, if not then there was a swap
let ai =arrCopy.indexOf(maxV);
let si =sarr.indexOf(maxV);
if (ai !== si && (i+1)!=arrL && pos !== 0){
cnt++;
};
}
console.log(cnt);
}
check([1, 2, 3, 4, 5, 6]);//Result should be 3
check([6,5,4,3,2,1]); //result should be 0
check([1,2,3,4]); //result should be 2
check([1,3,2,5,4,6]); //result should be 3
check([1,2,10,4,5,6,7,8,9,3,12,11]);//result should be 6
check([ 49, 37, 9, 19, 27, 3, 25, 11, 53,  42, 57, 50, 55,  56, 38, 48, 6, 33, 28, 8, 20, 31, 51, 14, 23, 4, 58, 52, 36, 22, 41, 47, 39, 2, 7, 13, 45, 1, 44, 32, 10, 15, 21, 30, 17,  60, 29, 5, 59, 12, 40, 24, 54, 46, 26, 43, 35, 34, 18, 16]);//result should be 54
Can someone please let me know what I'm doing wrong?
I would start with a copy of the array in descending order for getting the right index of the items.
For practical reasons, (or just a shorter conception of the loop with including check and decrement), I loop from the end of the array.
Then I check the value of array and reversed at the dame index and go on with the iteration.
If not the same value, the items at the wanted position i and the actual position p are swapped and the count incremented.
At the end the count is returned.
function check(array) {
var reversed = array.slice().sort((a, b) => b - a),
count = 0,
i = array.length,
p;
while (i--) {
if (array[i] === reversed[i]) continue;
p = array.indexOf(reversed[i]);
[array[i], array[p]] = [array[p], array[i]];
count++;
}
console.log(...array);
return count;
}
console.log(check([1, 2, 3, 4, 5, 6])); // 3
console.log(check([6, 5, 4, 3, 2, 1])); // 0
console.log(check([1, 2, 3, 4])); // 2
console.log(check([1, 3, 2, 5, 4, 6])); // 3
console.log(check([1, 2, 10, 4, 5, 6, 7, 8, 9, 3, 12, 11])); // 6
console.log(check([ 49, 37, 9, 19, 27, 3, 25, 11, 53,  42, 57, 50, 55,  56, 38, 48, 6, 33, 28, 8, 20, 31, 51, 14, 23, 4, 58, 52, 36, 22, 41, 47, 39, 2, 7, 13, 45, 1, 44, 32, 10, 15, 21, 30, 17,  60, 29, 5, 59, 12, 40, 24, 54, 46, 26, 43, 35, 34, 18, 16])); // 54
.as-console-wrapper { max-height: 100% !important; top: 0; }
function minimumSwaps(arr) {
var count = 0;
arr.sort((a, b) => {
if (a < b) {
count++;
}
});
return count;
}
console.log(minimumSwaps([1, 2, 3, 4, 7, 6, 5]));

Nested for loop with 2 dimensional array

How can I replace the numbers in the array which can be multiplied by 2 the string "even" and also for "odd".
var numbers = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < numbers[i].length; j++) {
if(numbers[i][j] % 2 === 0) {
numbers[i][j] += " even";
} else {
numbers [i][j] += " odd";
}
console.log(numbers[j][i]);
}
}
If you mean replace the number by string , you can do this but the arrays must defined to be any :
const numbers: any = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < numbers[i].length; j++) {
if ( numbers[i][j] % 2 === 0) {
numbers [i][j] = 'even';
} else {
numbers [i][j] = 'odd';
}
}
}
You need to switch the indices, for displaying the actual element. If not, you get some elements without changed values.
console.log(numbers[i][j]);
// ^ ^
var numbers = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < numbers[i].length; j++) {
if (numbers[i][j] % 2 === 0) {
numbers[i][j] += " even";
} else {
numbers[i][j] += " odd";
}
console.log(numbers[i][j]);
}
}

Calculate quintiles/deciles from an array of numbers

Given the following array:
[13, 468, 3, 6, 220, 762, 97, 16, 522, 69, 119, 2895, 1255, 49, 19, 261, 9, 140, 55, 20, 6, 22, 6, 17, 115]
I need to calculate the value that is at the 20th, 40th, 60th, and 80th percentile. The steps would be to order the array from low to high, count the total number of values, determine what value is at the 20th percentile, etc. (for example, if there are 10 numbers in order from low to high, the 2nd value would be the 20th percentile).
This is stored in a variable and I know I can sort the numbers like this:
ticks6.sort();
and get the number of values in the array with this:
var newticks=ticks6.length;
I have no idea how to do the next part though where I figure out the percentiles, but looking for a solution in jquery or javascript.
Use like this:
var arr = [13, 468, 3, 6, 220, 762, 97, 16, 522, 69, 119, 2895, 1255, 49, 19, 261, 9, 140, 55, 20, 6, 22, 6, 17, 115];
arr.sort();
var len = arr.length;
var per20 = Math.floor(len*.2) - 1;
console.log(arr[per20]);
//similarly
var per40 = Math.floor(len*.4) - 1;
console.log(arr[per40]);
The Simple Statistics library has a quantile function you can use for this:
ss.quantile([13, 468, 3, 6, 220, 762, 97, 16, 522, 69, 119, 2895, 1255, 49, 19, 261, 9, 140, 55, 20, 6, 22, 6, 17, 115], 0.2)
=> 13
You can easely sort your array :
console.log([13, 468, 3, 6, 220, 762, 97, 16, 522, 69, 119, 2895, 1255, 49, 19, 261, 9, 140, 55, 20, 6, 22, 6, 17, 115].sort(function(a,b){return a-b}))
Get the length of the array : myArray.length.
And the 20th percile parseInt(myArray.length * 0.2) => 2
Something like this:
tricks6.sort();
var length = tricks6.length;
var twentieth = sorted[math.floor((length-1)*.2)] //do for all

Categories