Combine all arrays in object into one array. - javascript

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)

Related

what is the shortest way to remove duplicate data/entries from an Array in Javascipt? [duplicate]

I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on Stack Overflow that looks almost exactly like it, but it doesn't fail.
So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
More answers from duplicate question:
Remove duplicate values from JS array
Similar question:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:
function onlyUnique(value, index, array) {
return self.indexOf(value) === index;
}
// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);
console.log(unique); // ['a', 1, 2, '1']
The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.
onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.
This solution works without any extra library like jQuery or prototype.js.
It works for arrays with mixed value types too.
For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.
If you want to keep the last occurrence of a value, simply replace indexOf with lastIndexOf.
With ES6 this can be shorten to:
// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((value, index, array) => array.indexOf(value) === index);
console.log(unique); // unique is ['a', 1, 2, '1']
Thanks to Camilo Martin for hint in comment.
ES6 has a native object Set to store unique values. To get an array with unique values you could now do this:
var myArray = ['a', 1, 'a', 2, '1'];
let unique = [...new Set(myArray)];
console.log(unique); // unique is ['a', 1, 2, '1']
The constructor of Set takes an iterable object, like an Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.
Updated answer for ES6/ES2015: Using the Set and the spread operator (thanks le-m), the single line solution is:
let uniqueItems = [...new Set(items)]
Which returns
[4, 5, 6, 3, 2, 23, 1]
I split all answers to 4 possible solutions:
Use object { } to prevent duplicates
Use helper array [ ]
Use filter + indexOf
Bonus! ES6 Sets method.
Here's sample codes found in answers:
Use object { } to prevent duplicates
function uniqueArray1( ar ) {
var j = {};
ar.forEach( function(v) {
j[v+ '::' + typeof v] = v;
});
return Object.keys(j).map(function(v){
return j[v];
});
}
Use helper array [ ]
function uniqueArray2(arr) {
var a = [];
for (var i=0, l=arr.length; i<l; i++)
if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
a.push(arr[i]);
return a;
}
Use filter + indexOf
function uniqueArray3(a) {
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// usage
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']
return unique;
}
Use ES6 [...new Set(a)]
function uniqueArray4(a) {
return [...new Set(a)];
}
And I wondered which one is faster. I've made sample Google Sheet to test functions. Note: ECMA 6 is not avaliable in Google Sheets, so I can't test it.
Here's the result of tests:
I expected to see that code using object { } will win because it uses hash. So I'm glad that tests showed the best results for this algorithm in Chrome and IE. Thanks to #rab for the code.
Update 2020
Google Script enabled ES6 Engine. Now I tested the last code with Sets and it appeared faster than the object method.
You can also use underscore.js.
console.log(_.uniq([1, 2, 1, 3, 1, 4]));
<script src="http://underscorejs.org/underscore-min.js"></script>
which will return:
[1, 2, 3, 4]
One Liner, Pure JavaScript
With ES6 syntax
list = list.filter((x, i, a) => a.indexOf(x) == i)
x --> item in array
i --> index of item
a --> array reference, (in this case "list")
With ES5 syntax
list = list.filter(function (x, i, a) {
return a.indexOf(x) == i;
});
Browser Compatibility: IE9+
Remove duplicates using Set.
Array with duplicates
const withDuplicates = [2, 2, 5, 5, 1, 1, 2, 2, 3, 3];
Get a new array without duplicates by using Set
const withoutDuplicates = Array.from(new Set(withDuplicates));
A shorter version
const withoutDuplicates = [...new Set(withDuplicates)];
Result: [2, 5, 1, 3]
Many of the answers here may not be useful to beginners. If de-duping an array is difficult, will they really know about the prototype chain, or even jQuery?
In modern browsers, a clean and simple solution is to store data in a Set, which is designed to be a list of unique values.
const cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
const uniqueCars = Array.from(new Set(cars));
console.log(uniqueCars);
The Array.from is useful to convert the Set back to an Array so that you have easy access to all of the awesome methods (features) that arrays have. There are also other ways of doing the same thing. But you may not need Array.from at all, as Sets have plenty of useful features like forEach.
If you need to support old Internet Explorer, and thus cannot use Set, then a simple technique is to copy items over to a new array while checking beforehand if they are already in the new array.
// Create a list of cars, with duplicates.
var cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
// Create a list of unique cars, to put a car in if we haven't already.
var uniqueCars = [];
// Go through each car, one at a time.
cars.forEach(function (car) {
// The code within the following block runs only if the
// current car does NOT exist in the uniqueCars list
// - a.k.a. prevent duplicates
if (uniqueCars.indexOf(car) === -1) {
// Since we now know we haven't seen this car before,
// copy it to the end of the uniqueCars list.
uniqueCars.push(car);
}
});
To make this instantly reusable, let's put it in a function.
function deduplicate(data) {
if (data.length > 0) {
var result = [];
data.forEach(function (elem) {
if (result.indexOf(elem) === -1) {
result.push(elem);
}
});
return result;
}
}
So to get rid of the duplicates, we would now do this.
var uniqueCars = deduplicate(cars);
The deduplicate(cars) part becomes the thing we named result when the function completes.
Just pass it the name of any array you like.
Using ES6 new Set
var array = [3,7,5,3,2,5,2,7];
var unique_array = [...new Set(array)];
console.log(unique_array); // output = [3,7,5,2]
Using For Loop
var array = [3,7,5,3,2,5,2,7];
for(var i=0;i<array.length;i++) {
for(var j=i+1;j<array.length;j++) {
if(array[i]===array[j]) {
array.splice(j,1);
}
}
}
console.log(array); // output = [3,7,5,2]
I have since found a nice method that uses jQuery
arr = $.grep(arr, function(v, k){
return $.inArray(v ,arr) === k;
});
Note: This code was pulled from Paul Irish's duck punching post - I forgot to give credit :P
Magic
a.filter(e=>!(t[e]=e in t))
O(n) performance - we assume your array is in a and t={}. Explanation here (+Jeppe impr.)
let unique = (a,t={}) => a.filter(e=>!(t[e]=e in t));
// "stand-alone" version working with global t:
// a1.filter((t={},e=>!(t[e]=e in t)));
// Test data
let a1 = [5,6,0,4,9,2,3,5,0,3,4,1,5,4,9];
let a2 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6, 2], [1, 12]];
let a3 = ['Mike', 'Adam','Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];
// Results
console.log(JSON.stringify( unique(a1) ))
console.log(JSON.stringify( unique(a2) ))
console.log(JSON.stringify( unique(a3) ))
The simplest, and fastest (in Chrome) way of doing this:
Array.prototype.unique = function() {
var a = [];
for (var i=0, l=this.length; i<l; i++)
if (a.indexOf(this[i]) === -1)
a.push(this[i]);
return a;
}
Simply goes through every item in the array, tests if that item is already in the list, and if it's not, pushes to the array that gets returned.
According to JSBench, this function is the fastest of the ones I could find anywhere - feel free to add your own though.
The non-prototype version:
function uniques(arr) {
var a = [];
for (var i=0, l=arr.length; i<l; i++)
if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
a.push(arr[i]);
return a;
}
Sorting
When also needing to sort the array, the following is the fastest:
Array.prototype.sortUnique = function() {
this.sort();
var last_i;
for (var i=0;i<this.length;i++)
if ((last_i = this.lastIndexOf(this[i])) !== i)
this.splice(i+1, last_i-i);
return this;
}
or non-prototype:
function sortUnique(arr) {
arr.sort();
var last_i;
for (var i=0;i<arr.length;i++)
if ((last_i = arr.lastIndexOf(arr[i])) !== i)
arr.splice(i+1, last_i-i);
return arr;
}
This is also faster than the above method in most non-Chrome browsers.
We can do this using ES6 sets:
var duplicatesArray = [1, 2, 3, 4, 5, 1, 1, 1, 2, 3, 4];
var uniqueArray = [...new Set(duplicatesArray)];
console.log(uniqueArray); // [1,2,3,4,5]
["Defects", "Total", "Days", "City", "Defects"].reduce(function(prev, cur) {
return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
}, []);
[0,1,2,0,3,2,1,5].reduce(function(prev, cur) {
return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
}, []);
After looking into all the 90+ answers here, I saw there is room for one more:
Array.includes has a very handy second-parameter: "fromIndex", so by using it, every iteration of the filter callback method will search the array, starting from [current index] + 1 which guarantees not to include currently filtered item in the lookup and also saves time.
Note - this solution does not retain the order, as it removed duplicated items from left to right, but it wins the Set trick if the Array is a collection of Objects.
// 🚩 🚩 🚩
var list = [0,1,2,2,3,'a','b',4,5,2,'a']
console.log(
list.filter((v,i) => !list.includes(v,i+1))
)
// [0,1,3,"b",4,5,2,"a"]
Explanation:
For example, lets assume the filter function is currently iterating at index 2) and the value at that index happens to be 2. The section of the array that is then scanned for duplicates (includes method) is everything after index 2 (i+1):
πŸ‘‡ πŸ‘‡
[0, 1, 2, 2 ,3 ,'a', 'b', 4, 5, 2, 'a']
πŸ‘† |---------------------------|
And since the currently filtered item's value 2 is included in the rest of the array, it will be filtered out, because of the leading exclamation mark which negates the filter rule.
If order is important, use this method:
// 🚩 🚩 🚩
var list = [0,1,2,2,3,'a','b',4,5,2,'a']
console.log(
// Initialize with empty array and fill with non-duplicates
list.reduce((acc, v) => (!acc.includes(v) && acc.push(v), acc), [])
)
// [0,1,2,3,"a","b",4,5]
This has been answered a lot, but it didn't address my particular need.
Many answers are like this:
a.filter((item, pos, self) => self.indexOf(item) === pos);
But this doesn't work for arrays of complex objects.
Say we have an array like this:
const a = [
{ age: 4, name: 'fluffy' },
{ age: 5, name: 'spot' },
{ age: 2, name: 'fluffy' },
{ age: 3, name: 'toby' },
];
If we want the objects with unique names, we should use array.prototype.findIndex instead of array.prototype.indexOf:
a.filter((item, pos, self) => self.findIndex(v => v.name === item.name) === pos);
This prototype getUnique is not totally correct, because if i have a Array like: ["1",1,2,3,4,1,"foo"] it will return ["1","2","3","4"] and "1" is string and 1 is a integer; they are different.
Here is a correct solution:
Array.prototype.unique = function(a){
return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });
using:
var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();
The above will produce ["1",2,3,4,1,"foo"].
You can simlply use the built-in functions Array.prototype.filter() and Array.prototype.indexOf()
array.filter((x, y) => array.indexOf(x) == y)
var arr = [1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 6, 9];
var newarr = arr.filter((x, y) => arr.indexOf(x) == y);
console.log(newarr);
[...new Set(duplicates)]
This is the simplest one and referenced from MDN Web Docs.
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)]) // [2, 3, 4, 5, 6, 7, 32]
Array.prototype.getUnique = function() {
var o = {}, a = []
for (var i = 0; i < this.length; i++) o[this[i]] = 1
for (var e in o) a.push(e)
return a
}
Without extending Array.prototype (it is said to be a bad practice) or using jquery/underscore, you can simply filter the array.
By keeping last occurrence:
function arrayLastUnique(array) {
return array.filter(function (a, b, c) {
// keeps last occurrence
return c.indexOf(a, b + 1) < 0;
});
},
or first occurrence:
function arrayFirstUnique(array) {
return array.filter(function (a, b, c) {
// keeps first occurrence
return c.indexOf(a) === b;
});
},
Well, it's only javascript ECMAScript 5+, which means only IE9+, but it's nice for a development in native HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium, ...).
That's because 0 is a falsy value in JavaScript.
this[i] will be falsy if the value of the array is 0 or any other falsy value.
Now using sets you can remove duplicates and convert them back to the array.
var names = ["Mike","Matt","Nancy", "Matt","Adam","Jenny","Nancy","Carl"];
console.log([...new Set(names)])
Another solution is to use sort & filter
var names = ["Mike","Matt","Nancy", "Matt","Adam","Jenny","Nancy","Carl"];
var namesSorted = names.sort();
const result = namesSorted.filter((e, i) => namesSorted[i] != namesSorted[i+1]);
console.log(result);
If you're using Prototype framework there is no need to do 'for' loops, you can use http://prototypejs.org/doc/latest/language/Array/prototype/uniq/ like this:
var a = Array.uniq();
Which will produce a duplicate array with no duplicates. I came across your question searching a method to count distinct array records so after uniq() I used size() and there was my simple result.
p.s. Sorry if i mistyped something
edit: if you want to escape undefined records you may want to add compact() before, like this:
var a = Array.compact().uniq();
I had a slightly different problem where I needed to remove objects with duplicate id properties from an array. this worked.
let objArr = [{
id: '123'
}, {
id: '123'
}, {
id: '456'
}];
objArr = objArr.reduce((acc, cur) => [
...acc.filter((obj) => obj.id !== cur.id), cur
], []);
console.log(objArr);
If you're okay with extra dependencies, or you already have one of the libraries in your codebase, you can remove duplicates from an array in place using LoDash (or Underscore).
Usage
If you don't have it in your codebase already, install it using npm:
npm install lodash
Then use it as follows:
import _ from 'lodash';
let idArray = _.uniq ([
1,
2,
3,
3,
3
]);
console.dir(idArray);
Out:
[ 1, 2, 3 ]
I'm not sure why Gabriel Silveira wrote the function that way but a simpler form that works for me just as well and without the minification is:
Array.prototype.unique = function() {
return this.filter(function(value, index, array) {
return array.indexOf(value, index + 1) < 0;
});
};
or in CoffeeScript:
Array.prototype.unique = ->
this.filter( (value, index, array) ->
array.indexOf(value, index + 1) < 0
)
Finding unique Array values in simple method
function arrUnique(a){
var t = [];
for(var x = 0; x < a.length; x++){
if(t.indexOf(a[x]) == -1)t.push(a[x]);
}
return t;
}
arrUnique([1,4,2,7,1,5,9,2,4,7,2]) // [1, 4, 2, 7, 5, 9]
It appears we have lost Rafael's answer, which stood as the accepted answer for a few years. This was (at least in 2017) the best-performing solution if you don't have a mixed-type array:
Array.prototype.getUnique = function(){
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
If you do have a mixed-type array, you can serialize the hash key:
Array.prototype.getUnique = function() {
var hash = {}, result = [], key;
for ( var i = 0, l = this.length; i < l; ++i ) {
key = JSON.stringify(this[i]);
if ( !hash.hasOwnProperty(key) ) {
hash[key] = true;
result.push(this[i]);
}
}
return result;
}
strange this hasn't been suggested before.. to remove duplicates by object key (id below) in an array you can do something like this:
const uniqArray = array.filter((obj, idx, arr) => (
arr.findIndex((o) => o.id === obj.id) === idx
))
For an object-based array with some unique id's, I have a simple solution through which you can sort in linear complexity
function getUniqueArr(arr){
const mapObj = {};
arr.forEach(a => {
mapObj[a.id] = a
})
return Object.values(mapObj);
}

.flat() is not a function, what's wrong?

The following code
function steamrollArray(arr) {
// I'm a steamroller, baby
return arr.flat();
}
steamrollArray([1, [2], [3, [[4]]]]);
returns
arr.flat is not a function
I tried it in Firefox and Chrome v67 and the same result has happened.
What's wrong?
The flat method is not yet implemented in common browsers (only Chrome v69, Firefox Nightly and Opera 56). It’s an experimental feature. Therefore you cannot use it yet.
You may want to have your own flat function instead:
Object.defineProperty(Array.prototype, 'flat', {
value: function(depth = 1) {
return this.reduce(function (flat, toFlatten) {
return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten);
}, []);
}
});
console.log(
[1, [2], [3, [[4]]]].flat(2)
);
The code was taken from here by Noah Freitas originally implemented to flatten the array with no depth specified.
This can also work.
let arr = [ [1,2,3], [2,3,4] ];
console.log([].concat(...arr))
Or for older browsers,
[].concat.apply([], arr);
Array.flat is not supported by your browser. Below are two ways to implement it.
As a function, the depth variable specifies how deep the input array structure should be flattened (defaults to 1; use Infinity to go as deep as it gets) while the stack is the flattened array, passed by reference on recursive calls and eventually returned.
function flat(input, depth = 1, stack = [])
{
for (let item of input)
{
if (item instanceof Array && depth > 0)
{
flat(item, depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}
As a Polyfill, extending Array.prototype if you prefer the arr.flat() syntax:
if (!Array.prototype.flat)
{
Object.defineProperty(Array.prototype, 'flat',
{
value: function(depth = 1, stack = [])
{
for (let item of this)
{
if (item instanceof Array && depth > 0)
{
item.flat(depth - 1, stack);
}
else {
stack.push(item);
}
}
return stack;
}
});
}
Similar issue, solved by using ES6 .reduce() method:
const flatArr = result.reduce((acc, curr) => acc.concat(curr),[]);
use _.flatten from lodash package ;)
var arr=[[1,2],[3,4],[5,6]];
var result=[].concat(...arr);
console.log(result); //output: [ 1, 2, 3, 4, 5, 6 ]
Another simple solution is _.flattenDeep() on lodash
https://lodash.com/docs/4.17.15#flattenDepth
const flatArrays = _.flattenDeep([1, [2], [3, [[4]]]]);
console.log(flatArrays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
const array = [
[
[6, 6],
[3, 3],
],
[[7, 7, [9]]],
]
function simplifyArray(array) {
const result = []
function recursivePushElem(arr) {
arr.forEach(i => {
if (Array.isArray(i)) recursivePushElem(i)
else result.push(i)
})
}
recursivePushElem(array)
console.log(result)
return result
}
simplifyArray(array)
you could simply use this [].concat(...objArrs) that would work the same as the flat() method and allow more compatibility in browsers
You can set your full array to a string then split it. .toString().split(',')
Updated due to community bot.
So basically if you want to flatten out an array that does contain any objects but strictly strings or numbers, by using .toString() it converts each element of the array to a string (if it isn't already), and then joins all of the elements together using a comma as a separator.
Once we have our string all separated by a comma we can use .split() to create an array.
NOTE*** The reason this wont work with objects is that .toString() will return [object object] as it is the default string representation of an object in JavaScript.
If your array consists solely of numbers than you would need to map through your array and convert each string number value to a number.
const array1 = [
['one', 'oneTwo'],
'two',
'three',
'four',
]
console.log('a1', array1.toString().split(','))
const numberArray = [1, 2, [3, 4, [5, 6]], [[7, [8,9]]], 10];
console.log(numberArray.toString().split(',').map(num => Number(num)));
Not sure if it is a valid answer however in my attemp to flat an array I employed the destructuring_assignment introduced in ES6.
// typeScriptArray:Array<Object> = new Array<Object>();
let concatArray = [];
let firstArray = [1,2,3];
let secondArray = [2,3,4];
concatArray.push(...firstArray);
concatArray.push(...secondArray);
console.log(concatArray);
It works like a charm even though I'm not sure if any broswer compatibily issues may arise.

How do I get this 'Sorted Union' function to work using Array.concat, in javaScript

I am going through this exercise on FCC which requires the following:
Write a function that takes two or more arrays and returns a new array
of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included
in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the
final array should not be sorted in numerical order.
This is my code:
function uniteUnique(){
var elm, exists = {},
outArr = [],
arr = [],
args = Array.prototype.slice.call(arguments);
args.forEach(function(arg) {
arr.concat(arg.filter(Boolean));
});
for(var i =0; i<arr.length; i++){
elm = arr[i];
if(!exists[elm]){
outArr.push(elm);
exists[elm] = true;
}
}
return arr;
}
My problem centers around this line.
args.forEach(function(arg) {
arr.concat(arg.filter(Boolean));
});
I'd like all the arguments/arrays to go through the filter method and then get concatenated, any help would be appreciated!
Boolean will not filter unique items, it will simply return Boolean(arg) value which is not the intended one.
Replace
args.forEach(function(arg) {
arr.concat(arg.filter(Boolean));
});
with
args.forEach(function(arg) {
arr.concat(arg.filter(function(val){
return arr.indexOf(val) == -1;
}));
});
This will only concatenate array items which are unique
Well may be you prefer the following single liner functional approach instead;
var getUniques = (...a) => a.reduce((p,c)=> p.concat(c)).reduce((p,c) => {!~p.indexOf(c) && p.push(c); return p},[]);
document.write("<pre>" + getUniques([1,2,3],[3,4,5],[3,4,5,6,7,8],[0,1,2,3,4,5,6,7,8,9]) + "</pre>");
The getUniques function returns an array of all uniques in the order of appearance. Note that there is no arguments object in the arrow functions but the ...rest parameters of ES6 work just as well for that purpose. Even if you don't like the functional approach the logic behind may influence you to implement the same functionality with conventional functions and for loops.
And an even more simplified version of the above one is as follows
var getUniques = (...a) => a.reduce((p,c) => {c.forEach(e => !~p.indexOf(e) && p.push(e)); return p});
document.write("<pre>" + getUniques([1,2,3],[3,4,5],[3,4,5,6,7,8],[0,1,2,3,4,5,6,7,8,9]) + "</pre>");
function union(arrays) {
const u = arrays.reduce(function(acc, iVal) {
return acc.concat(iVal);
})
return [...new Set(u)];
}
var arr1 = [5, 10, 15];
var arr2 = [15, 88, 1, 5, 7];
var arr3 = [100, 15, 10, 1, 5];
console.log(union([arr1, arr2, arr3])); // should log: [5, 10, 15, 88, 1, 7, 100]

Trouble understanding memoize implementation

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.

Concatenate JSON arrays in a JSON objects in javascript

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).

Categories