Changing an array to an object - javascript

My question is it possible to change and array into an object?
The following code counts the number of occurrences of each word in an array.
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
changedString = string.replace(/,/g, " "), // remove the array elements
split = changedString.split(" "), // split the string
words = [];
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
Is it possible to change it so that instead of returning an array like this:
[ Not: 1,
long: 1,
left: 2,
grab: 1,
an: 4,
Easter: 5,
bargain: 1,]
instead it returns an object like this? { word: 'Not' num: 1 } etc.

You can use Object.key() and Array#map() for converting an object into an array of objects.
var obj = { Not: 1, long: 1, left: 2, grab: 1, an: 4, Easter: 5, bargain: 1 },
array = Object.keys(obj).map(function (k) { return { word: k, num: obj[k] }; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
// edit sorting
array.sort(function (a, b) { return a.num - b.num; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Related

How to take an array, and insert commas between each item?

I am trying to understand how to take an array like [1,2,3,4,5] and then between each index, add a , so the array becomes [1, ', ', 2, ', ', 3, ', ', 4, ', ', 5]
I know it sounds stupid but I'm having some issues with it.
Basically, I want to use something like splice() method, so that I can iterate over the array and each odd index, I can do splice(index, 0, ', ').
You can use .reduce method which accepts as parameter a callback function.
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single
value.
var array=[1,2,3,4,5];
console.log(array.reduce(function(a,b){
return a.concat(b).concat(",");
},[]).slice(0,-1));
Use .reduce()
Start with empty array
Push an element of array then push ', '
At last remove last ', ' using .pop()
var array1 = [1, 2, 3, 4, 5]
var array2 = array1.reduce(function(acc, val) {
acc.push(val);
acc.push(', ');
return acc;
}, []);
array2.pop();
console.log(array2);
You can use reduce to create a new array with the inserted values:
function weaveArray(array, weaveValue) {
const {length} = array;
return array.reduce((result, value, i) => {
if(i < length - 1) {
result.push(value, weaveValue);
} else {
result.push(value);
}
return result;
}, []);
}
console.log(
weaveArray([1,2,3,4,5], ",")
);
console.log([1,2,3,4,5].reduce(function(acc, val, idx, list) {
acc.push(val);
if (idx < list.length - 1) {
acc.push(',');
}
return acc;
}, []));
With just two methods:
Edit
If you want to save your commas use some regexp instead:
var c = a.join(', , , ').split(/\s(?=,\s)/);
var a = [1,2,3,4,5];
var b = a.join(' , ').split(' ');
var c = a.join(', , , ').split(/\s(?=,\s)/);
console.log(b,c);
Short solution using Array.prototype.join(), Array.prototype.map() and String.prototype.match() functions:
var arr = [1,2,3,4,5],
newArr = arr.join(',').match(/\w+|\W+/g).map(function(v){
return (isNaN(v))? v : +v; // considering numeric values
});
console.log(newArr);
You wanted splice approach? Here it is:
var arr = [1,2,3,4,5];
for (var i = 1; i < arr.length; i+=2) {
arr.splice(i, 0, ',');
}
console.log(arr);
You can use a variable at .splice() to increment index by 2
var arr = [1,2,3,4,5];
for (let i = 1, len = arr.length * 2; arr.length < len - 1; arr.splice(i, 0, ","), i += 2);
console.log(arr);

Can i sort nested array using nested sort()?

This should be the input array
var a = [2,1,3,4,1,[4,6,2,4],2,4,1];
For the output i have two cases :- (index of internal array is not changing)
a = [1,1,2,3,4,[2,4,4,6],1,2,4]
and
a = [1,1,1,2,2,[2,4,4,6],3,4,4]
This is what i am trying to use :-
a.sort(function(a,b){
if(b instanceof Array){
b.sort();
}
})
Array.sort() is not built to handle partial Arrays, what you would need in your case, but we can work around this problem by pre-processing the data (wrapping it with additional information), then sorting and at the end, extracting the original values:
case 1: sorting the parts between the Arrays
[2,1,3,4,1,[4,6,2,4],2,4,1] -> [1,1,2,3,4,[2,4,4,6],1,2,4]
function sort1(arr){
//I add an artificial "property" of to the values, to "describe" the groups, and to be able to sort by
//each Array is it's own group (so they stay in order), and the values in between share the same group
var group = 0,
isArray = false;
//an intermediate Array holding all the information (in order) to either apply it to the current Array, or to return (map) it as a new Array
var intermediate = arr.map(function(v,i){
//last value was an Array, this is the first value after an Array, start a new group
if(isArray) ++group;
if(isArray = Array.isArray(v)){ //update isArray
v = sort1(v); //recursive sorting
++group; //the last group just ended here
}
//return a composition, that contains all the data I need to sort by
return {
group: group,
value: v
}
}).sort(function(a, b){
//forst sort by group, and (only) if two values share the same group, sort by the original value
return a.group - b.group || a.value - b.value
});
//apply data to current Array
intermediate.forEach(function(obj, i){ arr[i] = obj.value });
return arr;
//return new Array
//return intermediate.map(function(obj){ return obj.value });
}
case 2: treating an Array like it's first value
[2,1,3,4,1,[4,6,2,4],2,4,1] -> [1,1,1,2,2,[2,4,4,6],3,4,4]
function sort2(arr){
//an utility to fetch the first non-array value recursively
function _value(v){
while(Array.isArray(v)) v = v[0];
return v;
}
var intermediate = arr.map(function(v, i){
if(Array.isArray(v)) v = sort2(v);
return {
index: i,
value: v,
sortingValue: _value(v)
}
}).sort(function(a, b){
return a.sortingValue - b.sortingValue || a.index - b.index;
});
//apply data to current Array
intermediate.forEach(function(obj, i){ arr[i] = obj.value });
return arr;
//return new Array
//return intermediate.map(function(obj){ return obj.value });
}
This is the perfect solution, use nested function invoke to sort array.
Firstly , store all the array position and sub array.
Secondly, extract numbers into new array,
Finally insert sorted array into same position as before.
var a = [2,1,3,4,1,[4,6,[4,5,[7,3,2,1,6],1,2],2,4],2,4,1];
function nestedSort(arr){
var items = [];
var numArr = [];
for ( key in arr){
if (arr[key] instanceof Array)
{
items.push({index:key,array:arr[key]});
}else{
numArr.push(arr[key]);
}
}
numArr.sort();
for (key in items){
numArr.splice(items[key].index,0,nestedSort(items[key].array));
}
return numArr;
}
console.log(nestedSort(a));
[
1,
1,
1,
2,
2,
[
2,
4,
[
1,
2,
[
1,
2,
3,
6,
7
],
4,
5
],
4,
6
],
3,
4,
4
]
Hope this can solve your problem. :)
You can loop over array and remove all sub arrays and save their index and then sort the new array and again push sorted sub arrays on specific indexes.
Sample
var arr = [2, 1, 3, 4, 1, [4, 6, 2, 4], 2, 4, 1];
var arr1 = [2, 1, 3, 4, 1, [4, 6, 2, 4], 2, 6, 4, [4, 5, 3], 1, 2, 1, 3]
var a = [2,1,3,4,1,[4,6,[4,5,[7,3,2,1,6],1,2],2,4],2,4,1];
function mySort(arr) {
var _list = [];
arr.forEach(function(item, index) {
if (Array.isArray(item)) {
_list.push({
index: index,
value: arr.splice(index, 1).pop()
});
}
});
arr.sort();
_list.forEach(function(item) {
arr.splice(item.index, 0, mySort(item.value))
})
return arr;
}
console.log(mySort(arr.slice()))
console.log(mySort(arr1.slice()))
console.log(mySort(a.slice()))
Edit 1
Inspired from joey-etamity's answer, have made it generic for nested structure.
No, you don't put the sort call in the comparison function. You would recurse through your arrays, bottom to top, and sort them one after the other. In your case you might not even need recursion if it's only one array in another:
a.forEach(function(element) {
if (Array.isArray(element))
element.sort(function compare(a, b) { return a-b; });
})
(I've chosen a simple numerical compare here).
Then you'd sort the outer array:
a.sort(function compare(a, b) {
if (Array.isArray(a)) a = a[0];
if (Array.isArray(b)) b = b[0];
return a - b;
})
(here compare takes the first element of the array to compare by that against the other numbers).
I suggest to splice the array if there is an element an array. Then sort the array and reassemble the array.
This proposal iterates from the back and keeps the array intact while splicing.
function sort(array) {
var i = array.length,
inside = [];
while (i--) {
if (Array.isArray(array[i])) {
inside.unshift({ pos: i, value: sort(array.splice(i, 1)[0]) });
}
}
array.sort(function (a, b) { return a - b; });
inside.forEach(function (a) {
array.splice(a.pos, 0, a.value);
});
return array;
}
var a = [2, 1, 3, 4, 1, [4, 6, 2, 4], 2, 4, 1];
console.log(sort(a));
I think this would be better to use Array.prototype.sort this way:
// var arr = [2, 1, 3, 4, 1, [4, 6, 2, 4], 2, 4, 1];
var arr = [2, 1, 3, 4, 1, [4, 6, 2, 4], 2, 6, 4, [4, 5, 3], 1, 2, 1, 3];
var chunks = chunkate(arr)
console.log(JSON.stringify(chunks));
chunks.forEach(ch => ch.sort(_sort));
var result = chunks.reduce((p, c) => p.concat(c));
console.log(JSON.stringify(result));
function _sort(a, b) {
var isAa = Array.isArray(a),
isAb = Array.isArray(b);
isAb && b.sort(_sort);
return (isAa || isAb) ? 0 : a - b;
}
function chunkate(arr) {
return arr.reduce((a, c) => {
Array.isArray(c) ? a.push(chunkate(c), []) : a[a.length - 1].push(c)
return a;
}, [[]]);
}
How it works?
If items to compare are are array then they shouldn't be replaced so by sending false sort function recognize that there is no need to replace. Otherwise the simple compare is the answer.
Edit
As discussed in comments, it's better to separate values to chunks and then sort each part then join parts again. If nesting depth is only one level you can use default sort (without _sort function) but be aware of array in array used for nested array. So the sort should be changed like this:
chunks.forEach(ch => Array.isArray(ch[0])? ch[0].sort(): ch.sort());

Javascript: how to sort array by object value in that array?

I want sort a Array in JavaScript by value of object which is that array holding.
For example:
Input
arr = [{id:[2, 'second']},{id:[8, 'eighth']},{id:[1, 'first']}];
My excepted output is:
sorted_arr = [{id:[8, 'eighth']},{id:[1, 'first']},{id:[2, 'second']}];
Note: Please give sort by alphabet
You can make a compare function like this which will do as require.
arr.sort(function(a, b){
return a["id"][0]-b["id"][0];
});
Suppose in case when both id's are equal, in that case if you want to do sorting on basis of your second parameter i.e first,second third then the code will be
arr.sort(function(a, b){
if(a["id"][0]===b["id"][0])
{
if(a["id"][1] < b["id"][1]) return -1;
if(a["id"][1] > b["id"][1]) return 1;
return 0;
}
return a["id"][0]-b["id"][0];
});
You can use sort()
arr = [{
id: [2, 'second']
}, {
id: [4, 'fourth']
}, {
id: [1, 'first']
}];
var sort = arr.sort(function(a, b) {
return a.id[0] - b.id[0];
});
document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');
If you want to sort based on the word in array then you need to compare the values
arr = [{
id: [2, 'second']
}, {
id: [4, 'fourth']
}, {
id: [1, 'first']
}];
var sort = arr.sort(function(a, b) {
if (a.id[1] > b.id[1]) return 1;
if (a.id[1] < b.id[1]) return -1;
return 0;
});
document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');

Javascript: Most Efficient Way of Summing Multiple Arrays by Key

I have a JSON object returned from a web service, which is an array of objects. I need to add the "data" arrays together to form a summed array. The JSON response looks like this:
[
{
"data":[
0,3,8,2,5
],
"someKey":"someValue"
},
{
"data":[
3,13,1,0,5
],
"someKey":"someOtherValue"
}
]
There could be N amount of objects in the array. The desired output for the above example would be:
[3, 16, 9, 2, 10]
I was intending on creating an empty array variable (var arr), then looping over the objects, and for each object, loop through the "data" key and for each key increment the corresponding key in arr by the value.
Is there a more efficient way of doing this using some sort of merge function?
How about this, I believe it should work for all cases.
var data = [{
"data": [
0, 3, 8, 2, 5
],
"someKey": "someValue"
}, {
"data": [
3, 13, 1, 0, 5
],
"someKey": "someOtherValue"
}];
var datas = data.reduce(function(a, b) {
b.data.forEach(function(x, i) {
a[i] = a[i] || 0;
a[i] += x;
});
return a;
}, []);
console.log(datas);
If every object has the same data length, you can try with:
var input; // Your input data
var output = [];
for (var i = 0; i < input[0].data.length; i++) {
output[i] = input.reduce(function(prev, item) {
return +(item.data[i]) + prev;
}, 0);
}
console.log(output);
// [3, 16, 9, 2, 10]
If every object has different data size:
var input; // Your input data
var i = 0, output = [];
while (true) {
var outOfIndex = true;
var sum = input.reduce(function(prev, item) {
if (item.data[i] !== undefined) {
outOfIndex = false;
}
return +(item.data[i]) + prev;
}, 0);
if (outOfIndex) {
break;
}
output[i++] = sum;
}
console.log(output);
// [3, 16, 9, 2, 10]
Slightly less imperative solution:
//zip takes two arrays and combines them per the fn argument
function zip(left, right, fn) {
var shorter = (right.length > left.length) ? left : right;
return shorter.map(function(value, i) {
return fn(left[i], right[i]);
});
}
//assuming arr is your array of objects. Because were using
//zip, map, and reduce, it doesn't matter if the length of the
//data array changes
var sums = arr
.map(function(obj) { return obj.data; })
.reduce(function(accum, array) {
//here we want to combine the running totals w/the current data
return zip(accum, array, function(l, r) { return l + r; });
});

How to sort an array sequencial in javascript?

I'm not sure if the title of this question is correct or not and also not sure what the appropriate keyword to search on google.
I have an array look like:
var myArray = [1,1,2,2,2,3,4,4,4];
and I want to sort my array into:
var myArray = [1,2,3,4,1,2,4,2,4];
Please in to my expected result. the order is ascending but duplicate value will repeated on last sequence instead of put it together in adjacent keys. So the expected result grouped as 1,2,3,4 1,2,4 and 2,4.
Thank you for your help and sorry for my bad English.
This code works. But it may exist a better solution.
// We assume myArray is already sorted
var myArray = [1,1,2,2,2,3,4,4,4],
result = [];
while (myArray.length) {
var value = myArray.shift();
// Find place
var index = 0;
while(result[index] && result[index][result[index].length - 1] == value) index++;
if(!result[index]) {
result[index] = [];
}
result[index][result[index].length] = value;
}
result.reduce(function(current, sum) {
return current.concat(sum);
});
console.log(result) // Display [1, 2, 3, 4, 1, 2, 4, 2, 4]
Here is my method using JQuery and it does not assume the array is already sorted.
It will iterate through the array and no duplicates to tempResultArray, once finished, it will then add them to the existing result and repeat the process again to find duplicates.
This is not the most efficient method, but it can be handled by one function and does not require the array to be sorted.
var myArray = [1,1,2,2,2,3,4,4,4],result = [];
while (myArray && myArray.length) {
myArray = customSort(myArray);
}
console.log(result);
function customSort(myArray){
var tempResultArray = [], tempMyArray = [];
$.each(myArray, function(i, el){
if($.inArray(el, tempResultArray ) === -1){
tempResultArray.push(el);
}else{
tempMyArray.push(el);
}
});
tempResultArray.sort(function(a, b){return a-b});
$.merge( result,tempResultArray)
return tempMyArray;
}
JSFiddle
This proposal features a straight forward approach with focus on array methods.
function sprout(array) {
return array.reduce(function (r, a) {
!r.some(function (b) {
if (b[b.length - 1] < a) {
b.push(a);
return true;
}
}) && r.push([a]);
return r;
}, []).reduce(function (r, a) {
return r.concat(a);
});
}
document.write('<pre>' + JSON.stringify(sprout([1, 1, 2, 2, 2, 3, 4, 4, 4]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(sprout([1, 2, 3, 7, 7, 7]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(sprout([1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7]), 0, 4) + '</pre>');
here's another solution:
var myArray = [1, 1, 2, 2, 2, 3, 4, 4, 4];
function mySequelArray(arr) {
var res = arguments[1] || [];
var nextVal;
var min = Math.min.apply(null, arr);
if (res.length > 0) {
nextVal = arr.filter(function (x) {
return x > res[res.length - 1]
}).sort()[0] || min;
} else {
nextVal = min;
}
res.push(nextVal);
arr.splice(arr.indexOf(nextVal), 1);
return (arr.length > 0) ? mySequelArray(arr, res) : res;
}
console.log(mySequelArray(myArray))
fiddle
My best approach will be to split your array into separate arrays for each repeated value, then arrange each separate array and join altogether.
UPDATED:
I wrote a quick code sample that should work if the same number in inputArray is not given more than twice. You could improve it by making it recursive thus creating new arrays for each new number and removing the limitation. Had some free time so i re-wrote a recursive function to sort any given array in sequence groups like you wanted. Works like a charm, inputArray does not need to be sorted and doesn't require any libraries. Jsfiddle here.
var inputArray = [3, 4, 1, 2, 3, 1, 2, 4, 1, 2, 5, 1];
var result = sortInSequence(inputArray);
console.log(result); //output: [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 1]
function sortInSequence(inputArray){
var inputArraySize = inputArray.length,
tempArray = [], //holds new array we are populating
sameValuesArray = [], //holds same values that we will pass as param in recursive call
rSorted = []; //init sorted array in case we have no same values
for(var i = inputArraySize; i > 0; i--){
var value = inputArray.pop();
tempArray.push(value);
var counter = 0,
tempArraySize = tempArray.length;
for(var j = 0; j < tempArraySize; j++){
if(tempArray[j] == value){
counter++;
}
}
if(counter == 2){
//value found twice, so remove it from tempArray and add it in sameValuesArray
var sameValue = tempArray.pop();
sameValuesArray.push(sameValue);
}
}
if(sameValuesArray.length > 0){
rSorted = sortInSequence(sameValuesArray);
}
tempArray.sort();
return tempArray.concat(rSorted);
}

Categories