Creating a 2D array from a 1D array in JavaScript - javascript

I have the following array:
let numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20];
I create a new array without the duplicate values:
let counter = [...new Set(array)];
//Output: [ 10, 20, 30, 50 ]
I want to instantiate the counter array as a 2D/nested array so that it looks like this:
//counter output: [[10,4][20, 3][30, 1][50,1]]
What's the best way to do this? The numbers array could have various elements and therefore the number of elements in the counter array could vary.

This answer is for the original question (how to create an array of [[10, 0],[20, 0],[30, 0],[50, 0]] from the Set):
Instead of spreading the Set, use Array.from() to create an array of pairs:
const numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20];
const counter = Array.from(new Set(numbers), v => [v, 0]);
console.log(counter);

Assuming you actually want that second sub-array index to represent the number of occurrences of each number (ed: confirmed now), you can collect the counts into a Map and then convert that to an array
let numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20];
const counter = [...numbers.reduce((map, n) =>
map.set(n, (map.get(n) ?? 0) + 1), new Map())]
console.info(JSON.stringify(counter)) // stringifying so it's all on one line
The array conversion works since Map supports the common entries format of
[ [ key, value ], [ key, value ], ... ]
and using spread syntax implicitly converts it to an entries array.

One way is take the ideas you have already used and map across those values returning new arrays with the value and an additional zero.
let numbers = [...new Set([10, 20, 20, 10, 10, 30, 50, 10, 20])].map(value=>[value,0]);

You can convert your original array into an object (hash map) to keep track of the count. And then convert it into to Object.entries() array.
const numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20];
let obj = {};
numbers.forEach(n => {
obj[n] = obj[n] || 0;
obj[n]++;
});
const counter = Object.entries(obj).map(e => [+e[0], e[1]]);
console.log(counter);

Related

Selecting elements from an array based on another array values in JavaScript

Sorry for this basic question... I am relatively new to JS.
I have two arrays and want to select values from one based on the values of the other.
For example, if I have
var student = [10, 11, 21, 30, 31, 14];
var class = [1, 1, 2, 3, 3, 1];
How would I proceed (ideally with filter and/or map) to get the list of student numbers in class = 1, for example.
I know how I would do it with a for-loop and push() function, but I think there should be a more elegant/concise way to perform that task in a single line command with map, filter or other functions.
Thanks in advance for any help.
Filtering the students by checking the index in the other array would be pretty simple:
var student = [10, 11, 21, 30, 31, 14];
var classes = [1, 1, 2, 3, 3, 1];
console.log(
student.filter((_, i) => classes[i] === 1)
);
Keep in mind you cannot use class as a variable name - it's reserved. Use something else.
class is a reserved word in JavaScript. To achieve the expected output, you can use .filter to return elements where classes[index] have the value of 1:
const students = [10, 11, 21, 30, 31, 14];
const classes = [1, 1, 2, 3, 3, 1];
const getStudentsInClassOne = (arr=[]) => {
if(arr.length !== classes.length) return;
return arr.filter((e,index) => classes[index]===1);
}
console.log( getStudentsInClassOne(students) );

Add index of multiple arrays together

I am trying to add the values of multiple arrays at each index.
Eg.
arr1 = [100, 110, 121]
arr2 = [20, 25, 27.5]
newArr = [120, 135, 148.5]
My current approach is below.
I am finding the percentage change between stocks each day (Day 1, Day 2, Day 3 etc)
Then I am moving to the next stock and I want to add the percentage change of stock 1 and stock 2 together. ie Append the new percentage change to the old percentage change.
What I am trying to do know is check if the index exists as a key in the object, and if it does, add the diff figure to this index.
If the index doesn't exist I want to just add the diff figure.
It is working when the index doesn't exist but when the index does exist (ie. The second, third stock etc) the old value for that index is just overwritten with the newer value.
I want to add them together.
Is there a simple clean solution for this?
accumPercent = {}
const portfolio = props.test.map((item) => {
let oldPrice = item.res.data.o[0]
item.res.data.o.map((item1, index) => {
let diff = ((item.res.data.c[index] - oldPrice) / oldPrice) * 100
oldPrice = item.res.data.c[index]
if (index in Object.keys(accumPercent)) {
accumPercent[index] = accumPercent[index] + diff
} else {
accumPercent[index] = diff
}
})
})
let example = [
{
o: [10, 20, 30]
},
{
o: [10, 40, 60]
}
]
You can use map like this:
const arr1 = [100, 110, 121]
const arr2 = [20, 25, 27.5]
const newArr = arr1.map((i, idx) => i + arr2[idx])
// result: [120, 135, 148.5]
Or if the arrays are in an object:
const test = {arr1: [100, 110, 121], arr2: [20, 25, 27.5]}
const newArr = test.arr1.map((i, idx) => i + test.arr2[idx])
// result: [120, 135, 148.5]
One more way :
let fr = []
arr1.forEach((d,index)=>{
fr.push(d + arr2[index])
})
console.log(fr)

Finding the index of an array in a two dimensional array?

I have two arrays. I want to find the index of currentArr positions in originalArr.
Both the arrays are updated on run time.
let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]]
Can anyone pls help me with this?
You can use the function map and the function findIndex to look for the matches.
This alternative checks the length as well as each index value using the function every.
I'm assuming the indexes should be at the same position
let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]];
let indexes = currentArr.map(a => originalArr.findIndex(ia => ia.length === a.length && ia.every((e, i) => e === a[i])));
console.log(indexes);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Since the inner arrays will always be in the same order, you could use JSON.stringify to compare the stringified version of arrays:
let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]];
let indexes = currentArr.map(c =>
originalArr.findIndex(o => JSON.stringify(o) === JSON.stringify(c)));
console.log(indexes);

Return Multiple items with the .filter() method - JavaScript

If I have an array with a set of numbers, and want to remove certain ones with the .filter method, I understand how to do this in when i need to remove a single item (or if i can use a mathematical expression), but can't get it to work with multiple items either purely by their value or position in the array.
In the following code I would like the new array selection to return the numbers 10, 12, 15
Also, I do need to do this with the filter() method only.
JS
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){
return num === [10, 12, 30];
});
You can use includes:
let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(function(num){
var good = [10, 12, 30]
return good.includes(num);
});
console.log(selection)
Of if you prefer the terseness of arrow function:
let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(num => [10, 12, 30].includes(num))
console.log(selection)
Forgive me if I do not understand it correctly, but if what you're looking for is to filter an array by the item's index, you can use the second parameter passed to the filter method's callback, which is the index.
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num, index){
return index > 0 && index < 4;
});
console.log(selection);
You do need a condition that will return true or false when using filter, so the simplest way to do this with the filter method would be:
let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){
if (num > 4 && num < 16) {return true};
});
The other way to do it would be filtering by position in the array and that would be better achieved with other array methods.
If I understand your question you want a function that takes a an array, checks if the elements are in your larger array and if they are there, removes them.
Filter might not be your best choice here because it doesn't alter the original array, it only makes a new array. Try using splice.
let random = [4, 10, 12, 15, 30];
function remove(array) {
for (var i = 0; i < array.length; i++) {
if(random.includes(array[i])){
random.splice(random.indexOf(array[i]), 1)
}
}
}
remove([10, 12, 30]);
console.log(random); // [4, 15]
I am assuming you want to remove because if you already know which elements you want why filter them out? why not just pass them into your function as a new array? filter will create a new array anyways.
But if you would like to remove elements from your first array the answer above might help.

interchange array using shift method

I am trying to interchange array and print it using shift method but not sure whether I can use it or not.
Code Snippet below.
var points = [40, 100, 1, 5, 25, 10];
//trying to achieve like anotherPoints array
//var anotherPoints = [1, 5, 100, 40, 25, 10];
for (index = 0; index < points.length; index++) {
points.shift();
console.log(points);
}
Some logic to get the desired result:
var points = [40, 100, 1, 5, 25, 10],
temp1 = [], temp2 = [], anotherArray;
points.forEach(function(val){
if(val < 10 ) {
temp1.push(val)
} else {
temp2.push(val);
}
});
anotherArray = temp1.sort().concat(temp2.sort(function(a,b){return b- a}));
alert(anotherArray);
It's not possible via shift or splice. Unless manually creating the array.
The shift() method doesn't shift or interchange the elements of an Array. It is similar to pop(), but it pops out the first element from the Array.
For example,
var points = [40, 100, 1, 5, 25, 10];
console.log(points.shift()); // 40
console.log(points); // [100, 1, 5, 25, 10]
As to your requirement of rearranging the elements of an Array, you will have to use Array.splice() method. Check out this question Reordering arrays.

Categories