I have a JSON response like this:
{"result":[["abc","de"],["fgh"],["ij","kl"]]}
I want the response to be in the form:
{"result":["abc","de","fgh","ij","kl"]}
How can I achieve this?
From the mozilla docs
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
var test={"result":[["abc","de"],["fgh"],["ij","kl"]]};
var tmp=[];
for(var i in test.result){
for(var j in test.result[i]){
tmp.push(test.result[i][j]);
}
}
test.result=tmp;
alert(JSON.stringify(test));
jsfiddle link http://jsfiddle.net/fu26849m/
jsFiddle
var arrayToFlatten = [[0, 1], [2, 3], [4, 5]];
Native (from Merge/flatten an array of arrays in JavaScript?):
var flattenedNative = arrayToFlatten.reduce(function(a, b) {
return a.concat(b);
});
alert(flattenedNative); // 0,1,2,3,4,5
jQuery (from How to flatten array in jQuery?):
var flattenedJQuery = $.map(arrayToFlatten, function(n) {
return n;
});
alert(flattenedJQuery); // 0,1,2,3,4,5
Native alternative (from Merge/flatten an array of arrays in JavaScript?):
var flattenedNativeAlt = [].concat.apply([], arrayToFlatten);
alert(flattenedNativeAlt); // 0,1,2,3,4,5
My first suggestion for this is you should create json directly as you want to use.
Do not modify it after you get.
You can also use this , this will give you value as you want.:
var mainText= JSON.parse('{"result":[["abc","de"],["fgh"],["ij","kl"]]}');
var arr = [];
for(var val1 in mainText.result)
{
arr = arr.concat(mainText.result[val1]);
}
mainText.result = arr;
console.log(JSON.stringify(mainText));
The reduce() and concat() functions can be combined to flatten an array:
var json = {"result":[["abc","de"],["fgh"],["ij","kl"]]};
function concatArrays(a, b) { return a.concat(b); }
json.result = json.result.reduce(concatArrays);
console.log(json); //{"result":["abc","de","fgh","ij","kl"]}
See it in action:
http://jsfiddle.net/cazomufn/
I like lodash' flatten (if you can live with another dependency.)
json.result = _.flatten(json.result);
// { result:['abc','de','fgh','ij','kl'] }
For example reduce isn't supported before IE9 but lodash would still work (compatibility build).
Related
I need your help arround array in JS.
I have a function where i need to check if the array passed in argument is one dimension or 2 dimension
let's say :
function test(array){
if(array is single dimension{
console.log("Single dimension");
}else{
console.log("2Dimension");
and the following should display :
test([1,2,3]); // Should log "Single dimension"
test([[1,2,3],[1,2,3]]); // Should log "2Dimension"
Any help will be really nice! Thank you!
How to know if an array is single dimension or multiple dimension?
JavaScript doesn't have multi-dimensional arrays; it has arrays of arrays. There's a subtle difference between those two things. Even more, a JavaScript can have entries that are arrays and other entries that aren't arrays, making it only partially "multi-dimensional."
If you need to know that an array doesn't contain any arrays (e.g., is one-dimensional), the only way is to check every entry in it to see if that entry is an array:
if (theArray.every(entry => !Array.isArray(entry)) {
// One dimensional
} else {
// Has at least one entry that is an array
}
Here's an example of an array that only has some entries that are arrays and others that aren't:
const a = [1, 2, ["a", "b"], 3];
console.log(a.length); // 4, not 5
console.log(Array.isArray(a[0])); // false
console.log(Array.isArray(a[2])); // true
You could take a recursive approach and check the first element for nested arrays.
function getDimension([array]) {
return 1 + (Array.isArray(array) && getDimension(array));
}
console.log(getDimension([1, 2, 3]));
console.log(getDimension([[1, 2, 3], [1, 2, 3]]));
Related to this one
Get array's depth in JavaScript
You can use function like this one :
function getArrayDepth(value) {
return Array.isArray(value) ?
1 + Math.max(...value.map(getArrayDepth)) :
0;
}
Then simply
const testArray = [1,2,3];
if (getArrayDepth(testArray) > 1){
console.log('One array');
}else{
console.log('Array in array')
}
It can be checked like that:
const arr = [1, 2, 3];
const multiDimensional = [
[1,2,3],
[1,2,3]
];
const isMultiDimensional = (arr) => {
const result = arr.reduce((a, c) => {
if (c.constructor === Array)
a = true;
return a;
}, false)
return result;
}
console.log(isMultiDimensional ([1, 2, 3]));
console.log(isMultiDimensional ([[1, 2, 3], [1, 2, 3]]));
I'm developing an extension for Google chrome and I'd like to combine all arrays in a certain object into one array instead of them being split. So right now, my console o
chrome.storage.sync.get(null, function(all) {
// this returns everything in chrome's storage.
}
It looks something like this in my console:
However, I'd like it to actually have all the arraries combined into one, as such:
Object
feed_0: Array[364]
I've tried this:
chrome.storage.sync.get(null, function(all) {
var test = {}; test = all;
delete test['currently.settings'];
console.log(test);
var alpha = [];
var result = 0;
for(var prop in test) {
if (test.hasOwnProperty(prop)) {
var second = alpha.concat(prop);
console.log(second);
// or Object.prototype.hasOwnProperty.call(obj, prop)
result++;
}
}
});
But this returns this:
Here is how to get one array from the all object:
var test = Object.values(all).flat();
In older JavaScript versions, that do not support these functions, go for:
var test = Object.keys(all).reduce( (acc, a) => acc.concat(all[a]), [] );
To assign it to a feed_0 property, is of course not the difficulty:
test = { feed_0: test };
You can combine your feed_N arrays into one property using Object.keys and Array#reduce:
var data = {
feed_0: [0, 1, 2],
feed_1: [3, 4, 5],
feed_2: [6, 7, 8],
feed_3: [9, 10, 11]
}
data = Object.keys(data).reduce(function(result, k) {
[].push.apply(result.feed_0, data[k])
return result
}, { feed_0: [] })
console.log(data)
I saw this function , though it works fine but I am bit puzzled about the function expressions. Here is the code
mapForEach(arr, fn) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(fn(arr[i]))
}
return newArr;
}
can anybody explain to nme what this rather complicated code is actually doing?
Lets say you have var array = [1, 2, 3, 5]; and then run var array2 = mapForEach(array, function(i) { return i * 2; })
array2 would then contain [2, 4, 6, 10].
So it returns a new array where you have the ability to modify each record with a function
mapForEach enumerates an array and calls a supplied function on each element.
example:
var a = [1, 2, 3];
console.log(mapForEach(a, (x) => x * 2));
would create a new array with the values (and output to console):
[2, 4, 6]
Basically it is an implementation of javascript native array function map, which creates a new array with the results of calling a provided function on every element in this array.
More info about mentioned function you can find here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Right now I have an array of the form [[1, 2], [3, 4], ...] and need to use an array of the keys [1, 3, ...] and was wondering if there was a javascript or d3 library function that took in the array of arrays and a function, then returned a new array according to the function. Something like this:
var data = [[1, 2], [3, 4]]
var keyArray = d3.transformArray(data, function(d) { return d[0]});
// keyArray = [1, 3]
So I can avoid looping over the data array again
var keyArray = [];
for (i = 0; i < data.length; i += 1) {
keyArray.push(data[i][0]);
}
// keyArray[1, 3]
This seems like a common enough thing to do using d3, but I wasn't sure if there's a specific name for this process of using a specific object and a function to create a new object of the same type.
you can use Array.prototype.map
x = [1,2,3].map(function(item){return item+1;});
this will result int [2,3,4]
read about this here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
How does answerKey[parameters] work? if Array.prototype.slice.call(arguments)
returns an array [157, 687], is answerKey[parameters] storing an array as key?
function memoize(mathProblem) {
var answerKey = {};
return function(){
var parameters = Array.prototype.slice.call(arguments);
if (answerKey[parameters]) {
console.log('returning cached');
return answerKey[parameters];
} else {
answerKey[parameters] = mathProblem.apply(this, arguments);
return answerKey[parameters]
}
}
};
var multiply = function(a, b){
return a*b;
}
var memoMultiply = memoize(multiply);
console.log(memoMultiply(157, 687));
=>
107859
console.log(memoMultiply(157, 687))
=>
returning cached
107859
The square bracket notation will convert an array into a string
var answerKey = {};
var params = [157, 687];
answerKey[params] = 107859;
answerKey['157,687']; // 107859
So yes, the key is the content of the array as a string. This is not great practice.
EDIT REQUESTED
In general I try to avoid depending on strings that are created from Array.prototype.toString() because it has some odd behavior
for example. Nested arrays are flattened
[2, [3, 4], 5].toString(); // '2,3,4,5'
This is losing information about the source array and is indistinguishable from
[2, 3, 4, 5].toString();
To get around issues like these I suggest passing the array through JSON.stringify();
JSON.stringify([2, [3, 4], 5]); // '[2,[3,4],5]'
JSON.stringify([2, 3, 4, 5]); // '[2,3,4,5]'
This example will work with .toString(); but I think its a bad habit.