Merging arrays to form array of arrays in JavaScript (ES6) - javascript

I have an arrays:
a = [1, 1, 1, 1]
Which should be merged with an array of arrays:
b = [[0],[0],[0],[0]]
To form a third:
c = [[0,1],[0,1],[0,1],[0,1]]
One way I have thought would be to run a .forEach on a and concatenate to each object of b. however, I'd like this so the list may become longer with, for example d=[2,2,2,2] creating e=[[0,1,2],[0,1,2],[0,1,2],[0,1,2]].
a = [1, 1, 1, 1];
b = [[0],[0],[0],[0]];
a.forEach((number,index) => {
b[index] = b[index].concat(number)
});
console.log(b);
Thanks!

The concat method does not append, it creates a new array that you need to something with.
You want map, not forEach - and you mixed up a and b in whose elements need to be wrapped in an array literal to be concatenated:
var a = [1, 1, 1, 1];
var b = [[0],[0],[0],[0]];
var c = a.map((number, index) => {
return b[index].concat([number]);
});
// or the other way round:
var c = b.map((arr, index) => {
return arr.concat([a[index]]);
});

You could use reduce() method with forEach() and create new array.
let a = [1, 1, 1, 1], b = [[0],[0],[0],[0]], d=[2,2,2,2,2]
const result = [b, a, d].reduce((r, a) => {
a.forEach((e, i) => r[i] = (r[i] || []).concat(e))
return r;
}, [])
console.log(result)

Related

removing duplicate elements in an array and also the elements which is repeated most in the array should come first in the new array

const source = [2, 9, 9, 1, 6];
const ans = source.filter((item, index, arr)=> arr.indexOf(item) === index);
console.log(ans);
here i'm able to remove the duplicate elements but how to make 9 which is repeated highest to come first in the new array??
any help would be appreciated
ans should be [9, 2, 1, 6]
This should work for all cases where array should be sorted by most number of reoccurrences.
const source = [2,1,9,9,6];
const indexes = [];
var ans = source.filter((item,index,arr)=>{
if(arr.indexOf(item) === index){
indexes.push({item:item,count:1})
return true;
}
else if(arr.indexOf(item) !== index){
indexes[indexes.findIndex(object=> object.item === item)].count++
return false;
}
return false;
})
ans =(indexes.sort((a,b)=>{return b.count - a.count}).map(obj =>obj.item))
console.log(ans)
If using more space is okay, you can use a hash map for counting elements and then convert it to an array.
Something like this.
let arr = [2, 9, 9, 1, 6];
// count elements
const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
// sort by values and convert back to array
const res = [...map.entries()].sort((a, b) => b[0] - a[0]).map((a) => {
return a[0]
});
console.log(res)
Try This
function removeAndSort(arr) {
var order = {};
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
if (value in order) {
order[value]++;
} else {
order[value] = 1;
}
}
var result = [];
for (value in order) {
result.push(value);
}
function sort(a, b) {
return order[b] - order[a];
}
return result.sort(sort);
}
console.log(removeAndSort([2, 9, 9, 1, 6]));
It's Absolutely Working, Check It
Instead of removing the duplicates with the code you have you need to find a way to create a frequency map to save the duplicates information. In this example I create a map using an object like this...
const freq = { 9: [9, 2], 1: [1, 1] ... };
which uses the current iterated element as a key in an object, and the value is the element along with its duplicate value. You can grab those arrays using Object.values, sort them by that duplicate value, and then map over that sorted nested array to produce the result.
Note, however, due to the sorting process this results in [9, 1, 2, 6].
const source = [2, 9, 9, 1, 6];
// `reduce` over the array creating a key/value pair where
// the value is an array - the first element is the element value,
// and the second value is its duplicate value
const nested = source.reduce((acc, c) => {
// If the object property as defined by the element
// value doesn't exist assign an array to it initialising
// the duplicate value to zero
acc[c] ??= [c, 0];
// Increment the duplicate value
++acc[c][1];
// Return the object for the next iteration
return acc;
}, {});
// We take the `Object.values` of the object (a series of
// nested arrays and sort them by their duplicate value,
// finally `mapping` over the sorted arrays and extracting
// the first element of each
const out = Object.values(nested).sort((a, b) => {
return b[1] - a[1];
}).map(arr => arr[0]);
console.log(out);
Additional documentation
Logical nullish assignment
function sortAndFilter(source) {
let duplicates = {};
//count the duplications
source.filter((item, index, arr) => {
if(arr.indexOf(item) != index)
return duplicates[item] = (duplicates[item] || 0) + 1;
duplicates[item] = 0;
})
//sort the numbers based on the amount of duplications
return Object.keys(duplicates).map(a => parseInt(a)).sort((a, b) => duplicates[b] - duplicates[a]);
}
Output: [ 9, 6, 2, 1 ]
This could do the job
this is best answer for your question
const source = [2, 9, 9, 1, 6];
function duplicate(array) {
let duplicates = array.filter((item, index) => array.indexOf(item) !== index);
return duplicates.concat(array.filter((item) => !duplicates.includes(item)));
}
console.log(duplicate(source));
function myFunction() {
const source = [2, 9, 9, 1, 6];
const ans = source.filter((item, index, arr)=> arr.indexOf(item) === index);
ans.sort((a, b) => b-a);
console.log(ans);
}
Output: [ 9, 6, 2, 1 ]

returning a new array of rankings based on initial array

I'm new to javascript and am trying to create a function that accepts an array of any length, and creates a new array with the rankings from that array (ie [10, 5, 20] would output [2, 3, 1]. This is my code so far ( i originally tried with a larger series of for loops finding the max each time but ran into issues getting them to repeat the same number of times as there are numbers in the array, so I switched to a sort method. Let me know if anyone can help point me in the right direction, thank you!!
function rankings(array){
let finalArray = [];
for (i = 0; i < array.length; i++) {//set up final array
finalArray[i] = array[i];
}
for(let list of array){
array.sort((a,b)=>b-a)//array sorted in order
}
for (i = array.length-1; i>=0; i--){
}
return finalArray;
}
If you like to get same ranks fro same values, cou could take the stored value for mapping.
const
rankings = array => array.map(
Map.prototype.get,
[...array]
.sort((a, b) => b - a)
.reduce((i => (m, v) => m.set(v, m.get(v) || i++))(1), new Map)
);
const result = rankings([10, 5, 20, 5]);
console.log(result);
Sort a clone (via spread) of the array, according to your ranking logic (descending in this case). Use Array.map() to create tuples of [value, index + 1], and generate a Map from the tuples.
Use Array.map() on the original array, and return the respective ranks from the Map:
function rankings(array) {
const ranks = new Map([...array].sort((a, b) => b - a)
.map((v, i) => [v, i + 1]))
return array.map(v => ranks.get(v));
}
const result = rankings([10, 5, 20]);
console.log(result);
To ignore repeat values, create a Set from the original array before spreading it:
function rankings(array) {
const ranks = new Map([...new Set(array)].sort((a, b) => b - a)
.map((v, i) => [v, i + 1]))
return array.map(v => ranks.get(v));
}
const result = rankings([10, 5, 20, 5]);
console.log(result);
You can give this a try:
var data = [10, 5, 20, 5, 4, 25];
var sorted = [...new Set([...data].sort((a,b)=>b-a))] // sorting and filtering the data
var result = data.map(elem=> getIndex = sorted.findIndex(v=>v==elem)+1);
console.log(result);

Sort an object according to an array with underscore

I am trying to sort an object comparing with an array. So the loop will look for specific values on the array, until it finds one, and put those 3 elements at the beginning and the rest at the end.
I am unsure what is the best way to do this any ideas?
It is something like that:
var arr = [1, 3, 2,4,5,6, 2];
var arrSimilar = [1,2,5]
var testSortBy = _.sortBy(arr, function(arrSimilar){
// [1,2,5,3,4,6,2]
});
console.log(testSortBy); // [1,2,5,3,4,6,2]
You could use sorting with map and take the index of the value of similar array as priority sorting and then take the index of all other values as order.
Important is to delete a used value of the similar array, because it is now in use and has no meaning for further similar values. That means, same values are sorted to their original relative index.
var array = [1, 3, 2, 4, 5, 6, 2],
similar = [1, 2, 5],
result = array
.map(function (a, i) {
var priority = similar.indexOf(a);
delete similar[priority]; // delete value, but keep the index of other items
return { index: i, priority: (priority + 1) || Infinity };
})
.sort(function (a, b) {
return a.priority - b.priority || a.index - b.index;
})
.map(function (o) {
return array[o.index];
});
console.log(result); // [1, 2, 5, 3, 4, 6, 2]
You can do that in the following way
Suppose A[] is the original array and B is the priority Array
The answer would be (B intersection A) concat (A-B)
var arr = [1, 3, 2,4,5,6];
var arrSimilar = [1,2,5];
let bInterA = arrSimilar.filter((e) => arr.indexOf(e) != -1);
let aDiffb = arr.filter((e) => arrSimilar.indexOf(e) == -1);
console.log(bInterA.concat(aDiffb));

Terse way to intersperse element between all elements in JavaScript array?

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = "&", so the output is [1, "&", 2, "&", 3].
Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).
Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:
_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex
or
_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted
or even
arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice
Edit: Haskell has this function, called intersperse
Using a generator:
function *intersperse(a, delim) {
let first = true;
for (const x of a) {
if (!first) yield delim;
first = false;
yield x;
}
}
console.log([...intersperse(array, '&')]);
Thanks to #Bergi for pointing out the useful generalization that the input could be any iterable.
If you don't like using generators, then
[].concat(...a.map(e => ['&', e])).slice(1)
A spread and explicit return in reducing function will make it more terse:
const intersperse = (arr, sep) => arr.reduce((a,v)=>[...a,v,sep],[]).slice(0,-1)
// intersperse([1,2,3], 'z')
// [1, "z", 2, "z", 3]
In ES6, you'd write a generator function that can produce an iterator which yields the input with the interspersed elements:
function* intersperse(iterable, separator) {
const iterator = iterable[Symbol.iterator]();
const first = iterator.next();
if (first.done) return;
else yield first.value;
for (const value of iterator) {
yield separator;
yield value;
}
}
console.log(Array.from(intersperse([1, 2, 3], "&")));
One straightforward approach could be like feeding the reduce function with an initial array in size one less than the double of our original array, filled with the character to be used for interspersing. Then mapping the elements of the original array at index i to 2*i in the initially fed target array would do the job perfectly..
In this approach i don't see (m)any redundant operations. Also since we are not modifying any of the array sizes after they are set, i wouldn't expect any background tasks to run for memory reallocation, optimization etc.
One other good part is using the standard array methods since they check all kinds of mismatch and whatnot.
This function returns a new array, in which the called upon array's items are interspersed with the provided argument.
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Array.prototype.intersperse = function(s){
return this.reduce((p,c,i) => (p[2*i]=c,p), new Array(2*this.length-1).fill(s));
}
document.write("<pre>" + JSON.stringify(arr.intersperse("&")) + "</pre>");
Using reduce but without slice
var arr = ['a','b','c','d'];
var lastIndex = arr.length-1;
arr.reduce((res,x,index)=>{
res.push(x);
if(lastIndex !== index)
res.push('&');
return res;
},[]);
If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.
From the docs:
Creates a new list with the separator interposed between elements.
Dispatches to the intersperse method of the second argument, if present.
R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js
You could use Array.from to create an array with the final size, and then use the callback argument to actually populate it:
const intersperse = (arr, sep) => Array.from(
{ length: Math.max(0, arr.length * 2 - 1) },
(_, i) => i % 2 ? sep : arr[i >> 1]
);
// Demo:
let res = intersperse([1, 2, 3], "&");
console.log(res);
ONE-LINER and FAST
const intersperse = (ar,s)=>[...Array(2*ar.length-1)].map((_,i)=>i%2?s:ar[i/2]);
console.log(intersperse([1, 2, 3], '&'));
javascript has a method join() and split()
var arr = ['a','b','c','d'];
arr = arr.join('&');
document.writeln(arr);
Output should be: a&b&c&d
now split again:
arr = arr.split("");
arr is now:
arr = ['a','&','b','&','c','&','d'];
if (!Array.prototype.intersperse) {
Object.defineProperty(Array.prototype, 'intersperse', {
value: function(something) {
if (this === null) {
throw new TypeError( 'Array.prototype.intersperse ' +
'called on null or undefined' );
}
var isFunc = (typeof something == 'function')
return this.concat.apply([],
this.map(function(e,i) {
return i ? [isFunc ? something(this[i-1]) : something, e] : [e] }.bind(this)))
}
});
}
you can also use the following:
var arr =['a', 'b', 'c', 'd'];
arr.forEach(function(element, index, array){
array.splice(2*index+1, 0, '&');
});
arr.pop();
My take:
const _ = require('lodash');
_.mixin({
intersperse(array, sep) {
return _(array)
.flatMap(x => [x, sep])
.take(2 * array.length - 1)
.value();
},
});
// _.intersperse(["a", "b", "c"], "-")
// > ["a", "-", "b", "-", "c"]
const arr = [1, 2, 3];
function intersperse(items, separator) {
const result = items.reduce(
(res, el) => [...res, el, separator], []);
result.pop();
return result;
}
console.log(intersperse(arr, '&'));
A few years later, here's a recursive generator solution. Enjoy!
const intersperse = function *([first, ...rest], delim){
yield first;
if(!rest.length){
return;
}
yield delim;
yield * intersperse(rest, delim);
};
console.log([...intersperse(array, '&')]);
export const intersperse = (array, insertSeparator) => {
if (!isArray(array)) {
throw new Error(`Wrong argument in intersperse function, expected array, got ${typeof array}`);
}
if (!isFunction(insertSeparator)) {
throw new Error(`Wrong argument in intersperse function, expected function, got ${typeof insertSeparator}`);
}
return flatMap(
array,
(item, index) => index > 0 ? [insertSeparator(item, index), item] : [item] // eslint-disable-line no-confusing-arrow
);
};
Here is also a version with reduce only:
const intersperse = (xs, s) => xs.reduce((acc, x) => acc ? [...acc, s, x] : [x], null)
const a = [1, 2, 3, 4, 5]
console.log(intersperse(a, 0))
// [1, 0, 2, 0, 3, 0, 4, 0, 5]
Updated for objects not using join method:
for (var i=0;i<arr.length;i++;) {
newarr.push(arr[i]);
if(i>0) {
newarr.push('&');
}
}
newarr should be:
newarr = ['a','&','b','&','c','&','d'];

How can I merge TypedArrays in JavaScript?

I'd like to merge multiple arraybuffers to create a Blob. however, as you know,
TypedArray dosen't have "push" or useful methods...
E.g.:
var a = new Int8Array( [ 1, 2, 3 ] );
var b = new Int8Array( [ 4, 5, 6 ] );
As a result, I'd like to get [ 1, 2, 3, 4, 5, 6 ].
Use the set method. But note, that you now need twice the memory!
var a = new Int8Array( [ 1, 2, 3 ] );
var b = new Int8Array( [ 4, 5, 6 ] );
var c = new Int8Array(a.length + b.length);
c.set(a);
c.set(b, a.length);
console.log(a);
console.log(b);
console.log(c);
for client-side ~ok solution:
const a = new Int8Array( [ 1, 2, 3 ] )
const b = new Int8Array( [ 4, 5, 6 ] )
const c = Int8Array.from([...a, ...b])
I always use this function:
function mergeTypedArrays(a, b) {
// Checks for truthy values on both arrays
if(!a && !b) throw 'Please specify valid arguments for parameters a and b.';
// Checks for truthy values or empty arrays on each argument
// to avoid the unnecessary construction of a new array and
// the type comparison
if(!b || b.length === 0) return a;
if(!a || a.length === 0) return b;
// Make sure that both typed arrays are of the same type
if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b))
throw 'The types of the two arguments passed for parameters a and b do not match.';
var c = new a.constructor(a.length + b.length);
c.set(a);
c.set(b, a.length);
return c;
}
The original function without checking for null or types
function mergeTypedArraysUnsafe(a, b) {
var c = new a.constructor(a.length + b.length);
c.set(a);
c.set(b, a.length);
return c;
}
if I have multiple typed arrays
arrays = [ typed_array1, typed_array2,..... typed_array100]
I want concat all 1 to 100 sub array into single 'result'
this function works for me.
single_array = concat(arrays)
function concat(arrays) {
// sum of individual array lengths
let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
if (!arrays.length) return null;
let result = new Uint8Array(totalLength);
// for each array - copy it over result
// next array is copied right after the previous one
let length = 0;
for(let array of arrays) {
result.set(array, length);
length += array.length;
}
return result;
}
As a one-liner, which will take an arbitrary number of arrays (myArrays here) and of mixed types so long as the result type takes them all (Int8Array here):
let combined = Int8Array.from(Array.prototype.concat(...myArrays.map(a => Array.from(a))));
For people who love one-liners:
const binaryData = [
new Uint8Array([1, 2, 3]),
new Int16Array([4, 5, 6]),
new Int32Array([7, 8, 9])
];
const mergedUint8Array = new Uint8Array(binaryData.map(typedArray => [...new Uint8Array(typedArray.buffer)]).flat());
function concat (views: ArrayBufferView[]) {
let length = 0
for (const v of views)
length += v.byteLength
let buf = new Uint8Array(length)
let offset = 0
for (const v of views) {
const uint8view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)
buf.set(uint8view, offset)
offset += uint8view.byteLength
}
return buf
}
I like #prinzhorn's answer but I wanted something a bit more flexible and compact:
var a = new Uint8Array( [ 1, 2, 3 ] );
var b = new Float32Array( [ 4.5, 5.5, 6.5 ] );
const merge = (tArrs, type = Uint8Array) => {
const ret = new (type)(tArrs.reduce((acc, tArr) => acc + tArr.byteLength, 0))
let off = 0
tArrs.forEach((tArr, i) => {
ret.set(tArr, off)
off += tArr.byteLength
})
return ret
}
merge([a, b], Float32Array)

Categories