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 have not started coding this yet because I would like to gather my thoughts and figure out the best way to tackle this problem.
I have a sorted array that contains objects with a category and name.
The array is sorted by category (the categories are A, B, and C). A will always be placed first before B and B will always be placed before C.
After the categories are determined it will also be sorted by name. (Category A apple will be before category A banana)
Here is the method I was thinking of.
Have an inventory class which has 4 arrays in it. The arrays will be split up by category (array A, array B, array C and the combined array). This is so when the category is checked it will go to the correct array and place the content into the correct location based on the name. Instead of checking 1 huge array it checks a smaller array. When the object gets added it will append array a b and c into the combined array.
This will be coded in js. I am writing this because I want to know if I am on the right track or if there is better logic to sorting an array by category and name.
You can chain the sortings by the or operator. Through js short circuiting, that will be quite efficient, e.g.:
yourArray.sort((a,b)=>
a.category.localeCompare(b.category)
|| a.name.localeCompare(b.name)
);
Fore more groups with the same comparing mechanism, like localeCompare, you could use an array with the keys. This is easy to maintain.
var keys = ['category', 'name'];
array.sort(function (a, b) {
var v;
return keys.some(function (k) {
return v = a[k].localeCompare(b[k]);
}) && v;
});
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I have 3 arrays. Lets say the first array has 3 elements, second array has 2 elements, and third array has 5 elements. When I concatenate them the array[3] will go to first element of the second array, array[6] will go to the second element of third array, because I first concatenate the first array with the second. If I concatenate the first array with the third, then concatenate the second array, array[3] will point to the first element of the third array.
don't understand your content, but according do your subject , I think below may help.
const a = [1,2,3]
const b = [4,5]
const c = [...a, ...b] // [1,2,3,4,5]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I have an empty object array called groups.
Which is initialised as:
const groups = [[],[],[]]
Now array objects will populate inside each of the arrays inside the root object in the following manner:
The first object will go into the first array, the second object will be paired with the first object in the first array,
the third object will go into the second and the fourth will be paired with the third object in the second array.
Once all the arrays have 2 objects, the next incoming object will go into the first array and then the second, and so on.
Once all the arrays have 3 objects, next incoming object will go into the first array and then the second, and so on.
I have tried if else, but I think this has a particular algorithm solution that I cannot figure out.
It would be great if you can point me to the right direction.
Further clarification
I tested the logic given below, while it is close to what I am looking for, but in my case there has to be a predefined set of [[],[],[],[],[]] 5 arrays inside a root array and each array cannot hold more than 5 objects maximum. And considering your example of using a numerical value as an object it would be something like this if the total number of objects are less than 10: [[1,2],[3,4],[5,6],[7,8],[9,10]] if more than 10 and less than 15: [[1,2,11],[3,4,12],[5,6,13],[7,8,14],[9,10,15]], if more than 15 less than 20: [[1,2,11,16],[3,4,12,17],[5,6,13,18]...] and so on.
The logic seems to first fill the sub arrays with 2 objects each, and then each next object is added in a round-robin order.
We could leave the initialisation of groups to be either an array of 3 sub arrays, or 5 sub arrays, or still some other number of sub arrays, and build it up from there.
This leads to the following logic:
let groups = [[], [], [], [], []];
let max = groups.length * groups.length;
let firstPhase = groups.length * 2;
for (let val = 0; val < max; val++) {
let index = val < firstPhase ? val >> 1 : val % groups.length;
groups[index].push(val+1); // +1 because you start numbering from 1.
console.log(JSON.stringify(groups));
}
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
As the title suggests, how do I make a new object containing the 7 first keys of another object using JS? :) This is the structure of the object I would like to copy the data from.
{"data":[{"id":2338785,"team1":{"id":10531,"name":"Just For Fun"},"team2":{"id":10017,"name":"Rugratz"},"result":"2 - 0","event":{"name":"Mythic Cup 5","id":5148},"format":"bo3","stars":0,"date":1578279271000},....],"last_update":1578329378792}
Let's say there are 100 keys like this one, and I only want to copy the 7 first ones into a new object in JS.
Well technically, you have only 2 keys in the given Object but if you mean the data object, here's what you can do.
const MyNewObject = Object.entries(YourObject)
const results = []
and a simple for loop
MyNewObject.forEach((pair,i) => {
// for the 8th item it breaks and doesn't push it to results array
if ( i === 7 ) break;
results.push(pair)
}
OR u use slice instead :
// a little bit neater , and u call remove the empty results array above
const thisNewResult = MyNewObject.slice(0,6)
and finally the results is an array of key value pairs and you should do this code to make a new object from the results entries
const finalResults = Object.fromEntries(results)
Please notice that this may not be the Order you want since Object.Entries gives you the same order as the order of for in loop (for more info visit Elements order in a "for (… in …)" loop)
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 7 years ago.
Improve this question
am confused what this code deos so can anyone explian it to me the reason behind it.
function diff(arr1, arr2) {
var newArr = [];
var h1 = Object.create(null);
arr1.forEach(function(e) {
h1[e] = e;
});
var h2 = Object.create(null);
arr2.forEach(function(e) {
h2[e] = e;
});
Object.keys(h1).forEach(function(e) {
if (!(e in h2)) newArr.push(h1[e]);
});
Object.keys(h2).forEach(function(e) {
if (!(e in h1)) newArr.push(h2[e]);
});
return newArr;
}
i found it when i was searching how to get the difference between javascript arrays
breif explanation will be help full
Comparing 2 Arrays and finding all the differences is slow. The reason is because the lookup time is not fast.
Say you have the following:
var arr1 = [1,2,3,4];
var arr2 = [5,6,7,8];
What you want is to find every value in arr1 that isn't in arr2, AND every value in arr2 that isn't in arr1. To do this, you loop over arr1 and ask "is this value in arr2?" But each time you ask that, you have to also loop over arr2. Then, you have to repeat this again with arr2, looking up each value in arr1.
This Javascript method speeds things up. In Javascript, Objects are created as a set of unique keys and their corresponding values. For instance:
var obj1 = {a: "string a", 6: "number 6"};
Now, I can say obj1['a'] and it will return "string a". Not only can the keys and values be any time (number, string, Object), but the lookup is instantaneous. We no longer have to look at every key in obj1, so if we can take advantage of this, our logic would be much faster.
The first thing this Javascript method does is convert both Arrays into Objects. It uses the Array values as both the Object key and value, and we end up with h1 and h2.
Then, it does the logic I mentioned above. It looks at every key in h1 (this optimization eliminated duplicate Array values, because the Object key must be unique), and if that key is not in h2, it adds the value to newArr. Then this repeats for all keys in h2.
Basically, it optimizes our search by reorganizing our slow Array values into fast key-value Objects, then does the necessary comparisons.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have two comma separated lists, the first is a list of possible values, and the second is a list of "selected" values. I need to create a list of all of the items in the first list that do not exists in the second list.
I could just split the first list into an array and use a "for" to go through the list using a string_pos to see if the first list item is contained in the second, but I'm wondering if there is a more efficient way to accomplish this.
Thanks!!
You can filter the possible list.
if the lists are strings, split or match them to get arrays.
var possible=[1,2,3,4],
selected=[2,4];
var unchosen=possible.filter(function(itm){
return selected.indexOf(itm)==-1;
});
unchosen
/* returned value: (Array)
1,3
*/
If you are looking for the best possible way, this is what you have to do
Convert the list to be checked, to an object, in liner time. Because, objects are technically hashtables, which offer faster lookups O(1)).
Then, iterate over the first list and check if the current element is there in the object or not. If it is not there, add it to the result.
var list1 = [1, 2, 3], list2 = [1, 2], dict2 = {};
list2.forEach(function(item) {
dict2[item] = true;
});
var result = list1.reduce(function(prev, current) {
if (dict2.hasOwnProperty(current) === false) {
prev.push(current);
}
return prev;
}, [])
console.log(result);
Output
[ 3 ]
The first thing you want to do is definitely to split the two comma separated lists into arrays of strings. Assume that they are formatted fairly reasonably, you can do this with
possible_values = possible_string.split(/,\s?/) //split on commas with a possible space
selected_values = selected_string.split(/,\s?/)
If you are willing to use outside libraries, underscore.js has a perfect function for this. The operation you are describing is the set difference operator, which is the difference function in underscore.
The result you want is the return value of calling
_.difference(possible_values, selected_values)