Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this Arrays
const array1 = ['546546546546', '01/01/2020', 'A'];
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];
The first value from array1 and Array3 is the same. But the rest is not the same.
I want to eliminate those that are repeated in the value 0 and concatenate what they have in 1 and 2.
To get something like this:
['546546546546', '01/01/2020 A - 05/01/2020 B'];
['866465465465', '01/01/2020 B'];
You can create a dictionary with the first element in the array as a key. I used Array.prototype.reduce to create a dictionary and finally extract the values out of the dictionary with Object.values will give your result
const array1 = ['546546546546', '01/01/2020', 'A'];
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];
// group it into a single array for looping
const input = [array1, array2, array3];
const groupedValues = input.reduce((group, [key, date, name]) => {
// if exist concat the date and name with previous value
if (group[key]) {
group[key][1] = `${group[key][1]} - ${date} ${name}`;
} else {
// initialize if doesnt exist
group[key] = [key, `${date} ${name}`];
}
return group;
}, {});
const output = Object.values(groupedValues);
console.log(output);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to add elements without using loops and the built-in method of the array like for , foreach etc) and built in methods(like reduce,map...) of array
How can we do the addition?
var arr =[1,2,2,3,4...];
arr length also dynamic.
You can use Spread ... operator like this
var arr1 = [1, 2, 3, 4];
var arr2 = [5,6,7,8];
console.log([...arr1, ...arr2]);
Addition as in sum?
const arr = [1,2,2,3,4];
// normal way
let sum = arr.reduce((a,b) => a+b)
console.log(sum)
// weird way not using loops but still using a built-in method
sum = eval(arr.toString().replace(/,/g,"+"))
console.log(sum)
You can use concat for that whice creates a new array and returns the result so arr1 and arr2 will remain unchanged.
const arr1 = [1, 2];
const arr2 = [3, 4,5,6,7,8];
const combined = arr1.concat(arr2);
console.log(combined);
console.log(arr1);
console.log(arr2);
If you want to mutate the original array you can use push and the spread operator (...):
const a = [1,2]
const b = [3,4,5,6]
a.push(...b)
console.log(a);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is the array of objects that is to be push to an array
[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
How to achieve this array below from the above
"array": [
[
[
11,
21
],
[
31,
41
],
[
10,
20
]
]
]
Use Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
Map it
let arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
let result = [arr.map(({a,b}) => [a,b])];
console.log(result);
Use reduce to form an array and then Object.values to extract the object prop values for each sub array.
const arr = [{
a: 11,
"b": 21
}, {
"a": 31,
"b": 41
}, {
"a": 10,
"b": 20
}];
const result = arr.reduce((acc, x) => {
const values = Object.values(x);
acc.push(values);
return acc;
}, [])
console.log({
array: result
});
[].concat(array.map((val)=>Object.values(val)))
If all you want to do is push each element of B into A you can do A.concat(B).
If you want to make a new array with all the values your can
c = ([]).concat(A,B)
For your array of objects with values, you could
c = []; for ( vals in b ) c.concat(Object.values(vals);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am looking for a way to not only find unique arrays within a multidimensional array, but also count how many times a particular array occurs.
For Example
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
// Code
???
// Results
uniqueArrays === [[1,2], [1,3], [1,4]]
theCount ==== [2, 1, 3]
Edit:
I didn't realize that I had to show my attempts of how I should solve a problem before I asked a question.
I do know how to count the length of an array use the length() method. I do know how to filter unique arrays from a multi-dimensional array. I did not post my attempts using those tools though because those two issues have been solved to death.
You can map each inner array to a stringified version of itself using .map(JSON.stringified). Now, using this new array, you can reduce it to an object which contains each stringified array as a key, and keeps the number of occurrences as its value. While reducing, you can check whether or not the object's key has already been set using a[k] = (a[k] || 0)+1. If it has already been set, it will use the current number stored at the key and increment it by 1, if it hasn't already been set it will set it equal to zero, and then increment it by 1 (which acts as the default value for any new keys (i.e newly seen arrays)).
Lastly, you can get the keys from your object which represent each unique array as strings using Object.keys(), and parse each back into a non-stringified array using JSON.parse. You can get the counts from your array by using Object.values() as this will get all the values (ie: the counters) of your reduced object and put them into an array.
See example below:
const arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
const arr_str = arr.map(JSON.stringify);
const arr_map = arr_str.reduce((a, k) => (a[k] = (a[k] || 0) + 1, a), {});
const uniqueArrays = Array.from(Object.keys(arr_map), JSON.parse);
const theCount = Object.values(arr_map);
console.log(uniqueArrays);
console.log(theCount);
you can use below code
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
var test = [], obj ={};
arr.forEach(val => {
if(test.indexOf(val.toString()) == -1){
test.push(val.toString());
obj[val.toString()] = 1;
uniqueArrays.push(val);
}else{
obj[val.toString()] += 1;
}
})
theCount = Object.values(obj);
console.log(uniqueArrays);
console.log(theCount);
Hope it will help you.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've got an array like this
var x = [[a, b, c],[d, e, f]];
and I need to get the following result
var x = [[b, a],[e, d]];
i.e. we need to change positions for two first elements and remove the last one?
Please, write function that can achieve this.
x = x.map(arr => arr.slice(0, 2).reverse());
You can use reduce to loop over each item, then slice it to remove the last item, reverse the array, then add it to the new array.
var x = [['a', 'b', 'c'],['d', 'e', 'f']];
let result = x.reduce((arr, val) => {
arr.push(val.slice(0,2).reverse())
return arr
}, [])
console.log(result)
You could map the result of a destructuring assignment and return a new array.
var x = [['a', 'b', 'c'],['d', 'e', 'f']];
let result = x.map(([a, b]) => [b, a]);
console.log(result)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi I have two javascripts arrays and I want to display result in below way (specified in desired result table):
array1 = ( '2013/01/02','2013/01/03','2013/01/02','2013/01/02' );
array2 = ( 'a' ,'b', 'c', 'a' );
I need result in below format but in HTML page:
2013/01/02 2013/01/03
a 2 0
b 0 1
c 1 0
hints: array1 1st value link with array2 1st value, array1 2nd value link with array2 2nd value ...
How many 2013/01/02 and a ? if we compare two arrays ? count is 2 but should display in matrix
To count unique values use:
array1 = [ '2013/01/02','2013/01/03','2013/01/02','2013/01/02' ];
array2 = [ 'a' ,'b', 'c', 'a' ];
var counts = {};
for (var i = 0; i < array1.length; i++) {
if (!counts[array1[i]])
counts[array1[i]] = {};
if (counts[array1[i]][array2[i]])
counts[array1[i]][array2[i]] += 1;
else
counts[array1[i]][array2[i]] = 1;
}
DEMO.
Using two foreach loops you get your desired table (JQuery.each DEMO).