javascript arrays difference [closed] - javascript

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.

Related

value extraction from array in javascript [closed]

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 2 years ago.
Improve this question
business=[0:{"name":{"en":'prateek'}},1:{"name":{"ar":'rahul'}}]
How I can extract the value of en and ar from this type of the repeted object in a array
The issue with your question is that you define business as an Array with the use of square brackets, but then proceed to use key value pairs directly within the array (via the usage ":"), which is reserved for objects and not arrays. I'd recommend researching both array and object datatypes, however simply put:
let myArray = [1, 2, 3, ...];
// only stores values which can be retrieved using the values index i.e. myArray[0]
let myObj = {"key1" : "value1", "key2" : "value2"};
// values are stored against keys, and can be accessed via the key i.e. myObj.key1
I think you've confused how objects and arrays should work. My guess is that you'd be better off with this structure:
let businesses = [];
businesses.push({enName: 'prateek', arName: 'rahul'});
console.log(businesses[0], businesses[0].enName, businesses[0].arName);
This way you're using an array to hold a collection of businesses and which are represented by objects. These objects in turn have attributes for enName and arName.
I think this would be a much clearer way of structuring your issue.

Copy first 7 keys in object into a new object [closed]

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)

How to create a new object from my existent object in Javascript [closed]

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 4 years ago.
Improve this question
How do I create a new object from my other object please? So I have this code:
var test = {
p1: [
'factorial',
'11'
],
p3: 'temp1',
x1: 'factorial'
};
and I want to get this:
Newobj = {
factorial: [
'p1',
'x1'
],
11: 'p1',
temp1: 'p3'
}
To explain more: the values from the first object will be the keys in the second, but as you see there is an array, I need to go through all the values. Plus, I don't want to get a repeated one. For example, factorial exists in two keys : p1 and x1 so factorial needs to be written only once but with an array containing from where we got it.
Thank you!!
I'm just a sucker for these map/reduce problems.
I would first create a map of test value to an array of test keys matching that value.
Then reduce that map to a plain object, taking the array value if its length is greater than one, otherwise just the first entry.
const test = {"p1":["factorial","11"],"p3":"temp1","x1":"factorial"}
// create an intermediary Map of keys and values
const newMap = Object.keys(test).reduce((map, key) => {
// force the value to an array for consistency and iterate
[].concat(test[key]).forEach(val => {
// create or add to the "key" to the array at map.get(val)
map.set(val, (map.get(val) || []).concat(key))
})
return map
}, new Map())
// now reduce the Map entries to a plain object
const newObj = Array.from(newMap).reduce((obj, [key, val]) => ({
...obj,
[key]: val.length > 1 ? val : val[0] // only use an array if more than one entry
}), Object.create(null)) // Object.create(null) creates a plain object
console.info(newObj)
Some advice though... I would make all the values arrays, even if there's only one entry. This create a consistent API for iterating and consuming your object.

Inserting, deleting, and adding objects into an array [closed]

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;
});

Get list of items in one list that are not in another [closed]

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)

Categories

Resources