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);
Related
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 2 years ago.
Improve this question
In my code I have 6 lists of objects of different sizes.
I need to go through them all in a specific order, from the smallest list to the largest.
var list_1 = [...] // length 24
var list_2 = [...] // length 4
var list_3 = [...] // length 3
var list_4 = [...] // length 4
var list_5 = [...] // length 11
var list_6 = [...] // length 2
// Need code here for loop each list in order asc
list_6.forEach(...) // length 2
list_3.forEach(...) // length 3
list_2.forEach(...) // length 4
list_4.forEach(...) // length 4
list_5.forEach(...) // length 11
list_1.forEach(...) // length 24
Does anyone have a simple solution ? Thanks
You could add the lists in an array, sort it and perform the loop
[list, list2, ...]
.sort((a, b) => a.length - b.length)
.forEach(array => array.forEach(...))
Put the lists into another list and sort them.
const list1 = [1, 2, 3, 4],
list2 = [1],
list3 = [1, 2, 3, 4, 5, 6, 7];
let listOfLists = [list1, list2, list3].sort((a, b) => a.length - b.length);
console.log(listOfLists);
listOfLists.forEach(list => {
list.forEach(itemInList => {
console.log(itemInList);
});
});
See StackBlitz example.
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 2 years ago.
Improve this question
I have an array like this :-
let arr = [1,2,3,4,5,6,7,8,9]
I want to remove its last element after every 20 seconds and then add it in the beginning of its own array and this process will continuous and should never stop
Try
function arrayCycler(arr) {
const newArray = [...arr];
const lastElement = newArray.pop();
newArray.unshift(lastElement);
return newArray;
}
let newArray = [1,2,3,4,5,6,7,8,9]; // will be changed on every 20 seconds
setInterval(() => {
newArray = arrayCycler(newArray);
}, 20000);
Use setInterval to update the list every 20 seconds.
https://www.w3schools.com/jsref/met_win_setinterval.asp
You can use slice to get the array without the last element.
arr.slice(0, arr.length - 1)
I'll let you put it all together
In plain Javascript
var arr=[1,2,3,4,5,6,7];
let circularList=setInterval( function(){
arr.unshift(arr.pop())
console.log(arr)
if(arr.length==0)
clearInterval(circularList)
},20000);
Here's an example using an immediately-invoked function. Here it loops every second for convenience so adjust the counter from 1000 to 20000.
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
(function loop(arr) {
console.log(JSON.stringify(arr));
setTimeout(() => {
// `pop` off the last element
// and `unshift` on to the beginning
// of the array
arr.unshift(arr.pop());
// Call `loop` again with the
// updated array
loop(arr);
}, 1000);
}(arr));
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);
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)