What is the fastest way to make objectIds unique in an Array?
For testing if 2 objectIds are equal, may I convert objectIds to other type, such as numbers or strings?
The easiest way would be to add the ids as keys of an object like this:
var array = [1, 2, 3, 4, 5, 6, 2, 3, 4]
var obj = {}
array.forEach(function(id){obj[id] = true})
array = Object.keys(obj)
Other alternatives would be sorting the array and using binary search and using some data structure like AVL tree.
Related
Sounds way more confusing than it actually is, but it is simple given an example:
Let's say I have an array like this - [1, 2, 3, 4, 5]
I want the numbers 2, 3 and 4 in their own array like this - [2, 3, 4]
One detail is that the array is completely random! It is all user inputted so I use keywords to find the section I want, like this - ["cmd", "|arg", "stuff", "blah", "|end"]
For this example I would like an array of the items between the keywords |arg and |end that looks like this - ["stuff", "blah"]
I have already found the position in the array of the two keywords but how would I go about making an array of the items between these keywords?
I have tried splicing and I have tried for, but for is not allowed in the game I am coding for and I just cannot seem to find out how to splice it. There has to be a better way and I am not sure what the Method would be called if there even is a Method that can accomplish this.
I don't have any real code to show, as it would be a complete and utter mess if I show it
Just started learning javascript 3 days ago
If you first check to see if that the array contains both values, then you can slice the array into another result array.
let ar = ["cmd", "|arg", "stuff", "blah", "|end"];
let arRes = [];
if(ar.includes("|arg") && ar.includes("|end")){
let idx1 = ar.indexOf("|arg") + 1;
let idx2 = ar.indexOf("|end");
arRes = ar.slice(idx1, idx2)
}
console.log(arRes)
This question already has answers here:
Transposing a 2D-array in JavaScript
(25 answers)
Closed 1 year ago.
I have an Array of Arrays, looking like this:
[
[val-1-1, val-1-2],
[val-2-1, val-2-2],
[val-3-1, val-3-2],
...
[val-n-1, val-n-2]
]
The Array can be really long and what I'd like to achieve is "split" this data structure into two Arrays like so:
[val-1-1, val-2-1, val-3-1, ... val-n-1] and [val-1-2, val-2-2, val-3-2, ... val-n-2].
I'm looking for an efficient method to perform this. I know that this is technically easy by looping and using indexes, but I was wondering if there is an efficient method available for this task, as the initial Array is long and I also have multiple of these initial Arrays of Arrays, so looping might take an unnecessarily long time.
For every column, just check if for that column there's an array in the resultant, if there's already an array then simply push the element, else create a new array and then push.
const transpose = (arr) =>
arr.reduce(
(m, r) => (r.forEach((v, i) => ((m[i] ??= []), m[i].push(v))), m),
[]
),
matrix = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
];
console.log(transpose(matrix));
I need some help finding symmetric difference of a multi dimensional array, and a simple array. The first value in each inner array of the multidimensional array cells is the index that compares to the simple array.
So
array1 = [1,4,6,7]
array2 = [[1,"more",12],[8,"some",12]]
the result should be something like:
compare(array1, array2) = //[4,6,7] // there are three differences when compared this way
compare(array2, array1) = //[8,"some",12] // there is only one difference when compared this way
I need to return an array that has both difference of array1 from array2 AND difference from array2 from array1 in the same format as the lead array.
Ideally these are not overwriting the existing arrays but creates a new with the output results. There won't be other array formats besides these two array formats.
Each compare can use a different function if it helps. You don't have to use the same function for both, but if you can, great.
I tried a few permutations of loop comparisons
Also solutions found here
How to get the difference between two arrays of objects in JavaScript
And of the simple array methods here
How to get the difference between two arrays in JavaScript?
But I just am not being successful. Can someone give me a hand, and also explain their solution? Any modern tools are fine as long as its broadly cross browser compatible. All my other code sticks to ES6, so that would be ideal. If whipping out a one liner solution please explain what is going on so I can learn.
Thanks!
Update # Dave, this made sense to me, but after it failed I started trying different filter methods and other techniques in the posts above, without much success.
let newNurkles = new Array();
for(var i = 0; i < nurkles.length; i++){
if(this.activeNurkles.includes(nurkles[i])){
} else {
newNurkles.push(nurkles[i]);// if not then push to array
}
}
console.warn("Nurkles to Add" + newNurkles);
This shows how to perform a disjunctive union on two arrays, one being single dimensional while the other is a multidimensional array.
The symmetry is determined by each element of the single with the first element of each sub-array in the multi. The multi will only be one level deep.
Uses: Array.prototype.map(), Array.prototype.filter()
Steps:
Map over the first input array
For each element, filter the second input to exclude those found in first input
Limit results to only the first array returned
Notes:
o is the iteration of array1
t is iteration of array2
t[0] represents the match key
t[idx] represents the current value of the sub-array being iterated
Results from array2 will produce a multidimensional array
const array1 = [1, 4, 6, 7];
const array2 = [[1, "more", 12],[8, "some", 12], [7, 3, 9], [2, 7, 5, 4], [4, 3]];
const oneToTwo = array2.map((t, idx) => array1.filter(o => t[idx] !== o))[0]
const twoToOne = array1.map(o => array2.filter(t => o !== t[0]))[0]
console.log(oneToTwo);
console.log(twoToOne)
I have output like this(Multi dimensional array);
(4) [Array(3), Array(2), Array(2), Array(2)]
0: (3) [9, 8, 9]
1: (2) [5, 6]
2: (2) [6, 7]
3: (2) [4, 4]
length: 4
__proto__: Array(0)
I would like to get each value and multiply them and return the value. How do I do that?
First of all you should probably check why the numbers are coming as an array if you need to join them into one number. But, working with what you've given to us...
First, you have to get each inner array and join it as one single number. The best approach I can imagine is casting each number inside to a string, concatenating them, and casting back to Number, like this:
const numbersArray = outerArray
.map(innerArray =>
innerArray.map(number => number.toString()).join(''))
.map(Number)
After having mapped the array, you can then reduce it to a single number, multiplying along the way (and starting at 1 since we don't want an initial value to change the result):
numbersArray.reduce((product, each) => product * each, 1)
I'm working on a (JavaScript/JQuery) project that requires me to save data as a file.
The data being stored is an array, which normally wouldn't be an issue because I can would just store it as a string and then split the string based on "," on loading the data again. However the array I need to store is an array of other arrays of data, some of which have a few layers of arrays.
My initial thought is to run a function which converts each array to a string starting at the lowest levels and then add some sort of identifier (eg '/////') between each entry to separate each array of data and use them as the thing to detect for a Split function. This however make the storing/loading of the data very complex and I was wondering if there is a better way of saving multi-layer array data in Javascript.
You can still save it as a string but the serialization should be something like JSON.
To convert to json (encode) use JSON.stringify. This returns a string that you can save to the file:
var json_string = JSON.stringify(my_array);
Afterwards, to decode the string in the file (after reading it) use JSON.parse
var my_array = JSON.parse(json_string);
You can use JSON.stringify to convert a multi-level array to a string. And then you can use JSON.parse to convert it back to an array. Once you have the string you can save and restore it and use these methods to re-create the array.
a = [1, 2, [3, 4, [5, 6, [7, 8], 9]]]
> [1, 2, Array[3]]
s = JSON.stringify(a)
> "[1,2,[3,4,[5,6,[7,8],9]]]"
a2 = JSON.parse(s)
> [1, 2, Array[3]]