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);
Related
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)
I think the example is the simplest.
I have this array : [10, 30, 55, 75, 94, 112] and the value 69.
I want to get: [55, 75, 94, 112]
So I want to filter out the smaller values but keep the closest.
an idea?
Something like this using filter.
var arr = [1, 3, 5, 7, 9, 11];
var value = 6;
function remove(arr, value) {
let copy = arr;
let newArr = arr.filter((arr, index) => !((arr < value) && (copy[index + 1] < value)))
console.log(newArr)
}
remove(arr, value) // [5, 7, 9, 11]
Just filter, and check if either this or the next value in the array is >= limit
const filter=(array, limit)=>array.filter((value,index)=>value>=limit||array[index+1]>limit);
console.log(filter([10, 30, 55, 75, 94, 112], 69));
Use Array.filter, Array.pop, Array.sort Array.concat
function f(val, array){
// array.sort( (a,b)=>a-b ); // if array isn't sorted, you must be use
return array.filter(e=>e>val).concat([array.filter(e=>e<val).pop()])
}
Given an input array arr and a value val:
Iterate over arr, splicing all elements greater than val into a separate array.
Append the maximum element left in arr to the new array.
arr = [1, 3, 5, 7, 9, 11];
val = 6;
new_arr = []; // Initialize new array
for (let i=0; i<arr.length; i++) { // Iterate over current array
if (arr[i]>val) { // If the current element is greater than the given value
new_arr.push(arr.splice(i, 1)[0]) // Splice it into the new array
i--; // Decrement i so as to not skip any elements
}
}
new_arr.unshift(Math.max(...arr)) // Add the closest value to the new array
console.log(new_arr);
Start by finding the closest delta for numbers that are under the limit. Then filter all numbers that are under the limit, and the their delta with the limit is not equal to the delta you've found in the previous step.
Note: this assumes that the numbers are unique, but they don't have to be sorted.
const fn = (arr, lim) => {
const closestSmallerDelta = arr.reduce((acc, n) =>
lim < n || lim - n > acc ? acc : lim - n
, Infinity)
return arr.filter(n => lim < n || lim - n === closestSmallerDelta)
}
console.log(fn([10, 30, 55, 75, 94, 112], 69));
// unsorted array
console.log(fn([112, 55, 75, 94, 10, 30], 69));
assuming the array is always sorted:
const deleteSmallerButLastOne = (array , refNum ) =>{
const finalArr = []
for(let [index, num] of array.entries()){
if(num < refNum && array[index + 1] >= refNum) finalArr.push(num)
if(num > refNum) finalArr.push(num)
}
return finalArr
}
I took this approach instead of modifying the original array just in case you need it for later.
Here's one possible approach (apparently assuming array is sorted). The idea is to find the very first item that is greater than or equal to lim; when you found it, there's no need to check the rest of an array (and that's what all the other answers do).
function processSorted(arr, lim) {
const i = arr.findIndex(el => el >= lim);
if (i === -1) // no elements greater than lim, return just the last one
return arr.slice(-1);
if (i === 0) // the first element is greater than lim, give back 'em all!
return arr;
return arr.slice(i - 1);
}
console.log(processSorted([10, 30, 55, 75, 94, 112], 69));
It's not sorted, it's possible to sort it anyway, or, if you really strive for n-only, go with one-iteration only approach:
function processUnsorted(arr, lim) {
const res = [];
let oneLess = -Infinity,
len = arr.length;
arr.forEach(el => {
if (el >= lim) res.push(el);
else oneLess = Math.max(oneLess, el);
});
if (oneLess !== -Infinity) res.unshift(oneLess);
return res;
}
console.log(processUnsorted([30, 55, 10, 94, 75, 112], 69));
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);
So, I have two scripts running in Node.js.
Script A outputs a whole number that is >= 40 and is <= 320.
Script B runs script A millions of times and needs to count how many times each number appears.
What is the best way to go about doing this? There has to be a better solution than typing let number40 = 0; let number 41 = 0; all the way up to 320.
How about having a map-enum-like object holding key as number and as per their occurrences, incrementing their value;
let obj = {};
let numbers = [50, 55, 120, 300, 150, 50, 300, 50];
numbers.forEach(function(num) {
obj[num] ? ++obj[num] : (obj[num] = 1);
});
console.log(obj);
Useing Map
let myMap = new Map();
let numbers = [50, 55, 120, 300, 150, 50, 300, 50];
numbers.forEach(function(num) {
let val = myMap.get(num) || 0;
myMap.set(num, ++val);
});
console.log(myMap);//check browsers console to check the value.
I have a little problem with my Javascript code. Here is my question :
I want to write a function, who take in input a table of numbers. If numbers situated in even index, be returned as the way it is. But, if numbers situated in odd index, be return multiplied by his index.
For example :
Input :
[5, 10, 15, 20, 25, 30, 50, 100]
Return :
[5, 10, 15, 60, 25, 150, 50, 700]
So, my code :
function multiplyNum(numbers) {
const multiply = numbers.map(function(number) {
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
return numbers
}
if (numbers[i] % 2 !== 0) {
return numbers
}
});
return multiplyNum
}
You don't need the for loop at all, you can get the index from the map and multiply the odd values:
function multiplyNum(numbers) {
return numbers.map(function(number, index) {
return index % 2 ? number * index : number;
});
}
console.log(multiplyNum([5, 10, 15, 20, 25, 30, 50, 100]));
You could map with a conditional operator as a check.
var array = [5, 10, 15, 20, 25, 30, 50, 100],
result = array.map((v, i) => i % 2 ? v * i : v);
console.log(result);