Angular5 - Compare Arrays and return matches - arrays

I need to compare two arrays and return the matches:
Array1
(13) ["0:EQSOLREENVIO", "1:EQPER", "2:EQCAN", "3:EQRECHKODOC", "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC", "5:EQINDEV", "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP", "7:EQENT", "8:EQDEV", "9:EQRCH", "10:EQADMIPDV", "11:EQCRE,EQRETENER", "12:EQRECOOFI"]
0: "0:EQSOLREENVIO"
1: "1:EQPER"
2: "2:EQCAN"
3: "3:EQRECHKODOC"
4: "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC"
5: "5:EQINDEV"
6: "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP"
7: "7:EQENT"
8: "8:EQDEV"
9: "9:EQRCH"
10: "10:EQADMIPDV"
11: "11:EQCRE,EQRETENER"
12: "12:EQRECOOFI"
length: 13
__proto__: Array(0)
Array2
(3) ["11", "0", "5"]
0: "11"
1: "0"
2: "5"
length: 3
__proto__: Array(0)
What I have tried:
const orderStatusCodes = this.orderInProgressCmsModel.orderStatusCodes.split("/");
const orderGroupsEditables = this.orderInProgressCmsModel.orderStatusLogEditables.split(",");
let groupFound = '';
const groupFound2 = [];
orderGroupsEditables.forEach((element2) => {
orderStatusCodes.forEach((element) => {
if (element.indexOf(element2) >= 0){
groupFound = element.split(":")[1];
groupFound2.push(groupFound);
}
});
});
Result:
(4) ["EQCRE,EQRETENER", "EQSOLREENVIO", "EQADMIPDV", "EQINDEV"]
0: "EQCRE,EQRETENER"
1: "EQSOLREENVIO"
2: "EQADMIPDV"
3: "EQINDEV"
length: 4
__proto__: Array(0)
When the numbers match from each array I need the code returned. I have been able to do this with the code I show but I would like to know if theres an easier way like using filter or something similar?

One thing to note is that depending on how big the arrays are, you might want to have a more performant algorithm. The solution presented in the question and the one supplied by #Mohammed Mortaga will loop through the second array for every element in the first array (in big O notation, that would be O(n*m)). This is doing a lot more work than is needed. You really only need to loop through each array a single time (in big O notation, that would be O(n+m)).
You can create a lookup table by looping through array1 that you could then use to lookup if the id exists (and readily have access to the corresponding code):
const regex = /^([^:]*):(.*)/;
const lookup = array1.reduce((acc, val) => {
const [, id, code] = regex.exec(val);
acc[id] = code;
return acc;
}, {});
Once you have your lookup table it is constant time complexity to get the code that corresponds to each element in your array2 (meaning for each item we don't need to search for a match, we can know in constant time if there is a match or not). Here you could use reduce:
const codes = array2.reduce((acc, id) => {
const code = lookup[id];
if (code) {
acc.push(code);
}
return acc;
}, []);
or you could use a one-liner:
const codes = array2.filter(id => lookup[id]).map(id => lookup[id]);
The one-liner would be slightly less performant because it is doing two looping operations, but that is relatively minor if the array is pretty small in length (and the big O notation would still be the same but the readability is increased).

Yes, you can achieve this using a single filter function like so:
const array1 = ["0:EQSOLREENVIO", "1:EQPER", "2:EQCAN", "3:EQRECHKODOC", "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC", "5:EQINDEV", "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP", "7:EQENT", "8:EQDEV", "9:EQRCH", "10:EQADMIPDV", "11:EQCRE,EQRETENER", "12:EQRECOOFI"];
const array2 = ["11", "0", "5"];
const result = array1.filter(e => array2.indexOf(e.match(/\d+/)[0]) > -1); // ["0:EQSOLREENVIO", "5:EQINDEV", "11:EQCRE,EQRETENER"]
In short, this code iterates over the first array extracting the digits and checks if they exist or not in the second array.
Hope this helps!

Related

Images from Json file does not show [duplicate]

How do you get the first element from an array like this:
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
I tried this:
alert($(ary).first());
But it would return [object Object]. So I need to get the first element from the array which should be the element 'first'.
like this
alert(ary[0])
Why are you jQuery-ifying a vanilla JavaScript array? Use standard JavaScript!
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Also,
Source, courtesy of bobince
Some of ways below for different circumstances.
In most normal cases, the simplest way to access the first element is by
yourArray[0]
but this requires you to check if [0] actually exists.
Another commonly used method is shift() but you should avoid using this for the purpose of accessing the first element.
Well, this method modifies the original array (removes the first item and returns it) but re-indexes what is left in the array to make it start from 0 (shifts everything down). Therefore the length of an array is reduced by one.
There are good cases where you may need this, for example, to take the first customer waiting in the queue, but it is very inefficient to use this for the purpose of accessing the first element.
In addition, this requires a perfect array with [0] index pointer intact, exactly as using [0];
yourArray.shift()
The important thing to know is that the two above are only an option if your array starts with a [0] index.
There are cases where the first element has been deleted, for example with delete yourArray[0], leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.
So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.
You can use find() to get the first element.
The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below).
(You can customize the condition to exclude null or other empty values too)
var firstItem = yourArray.find(x=>x!==undefined);
I'd also like to include filter() here as an option to first "fix" the array in the copy and then get the first element while keeping the original array intact (unmodified).
Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).
var firstItem = yourArray.filter(x => typeof x!==undefined).shift();
Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach(), for example.
Another one I have seen in some projects is splice() to get the first item in an array and then get it by index:
var firstItem = yourArray.splice(0, 1)[0];
I am not sure why you would do that. This method won't solve the problem with holes in an array (sparse array). It is costly as it will re-index the array, and it returns an array that you have to access again to get the value. For example, if you delete the first couple of elements, then splice() will return undefined instead of the first defined value from the array.
Both find() and filter() guarantee the order of elements, so are safe to use as above.
**(I see some people suggest using loops to get the first element, but I would recommend against this method. Obviously, you can use any loop to get a value from an array but why would you do that?
Readability, optimization, unnecessary block of code etc. When using native functions, the browser can better optimize your code. And it may not even work with some loops which don't guarantee the order in iteration.
By the way, forEach() doesn't solve the issue as many suggest because you can't break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value, but why?**
Using ES6 destructuring
let [first] = [1,2,3];
Which is the same as
let first = [1,2,3][0];
You can just use find():
const first = array.find(Boolean)
Or if you want the first element even if it is falsy:
const first = array.find(() => true)
Or if you want the first element even if it is falsy but not if it is null or undefined (more information):
const first = array.find(e => typeof e !== 'undefined')
Going the extra mile:
If you care about readability but don't want to rely on numeric incidences you could add a first()-function to Array.prototype by defining it with Object​.define​Property() which mitigates the pitfalls of modifying the built-in Array object prototype directly (explained here).
Performance is pretty good (find() stops after the first element) but it isn't perfect or universally accessible (ES6 only). For more background read #Selays answer.
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(e => true) // or this.find(Boolean)
}
})
To retrieve the first element you are now able to do this:
const array = ['a', 'b', 'c']
array.first()
> 'a'
Snippet to see it in action:
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(Boolean)
}
})
console.log( ['a', 'b', 'c'].first() )
Element of index 0 may not exist if the first element has been deleted:
let a = ['a', 'b', 'c'];
delete a[0];
for (let i in a) {
console.log(i + ' ' + a[i]);
}
Better way to get the first element without jQuery:
function first(p) {
for (let i in p) return p[i];
}
console.log( first(['a', 'b', 'c']) );
If you want to preserve the readibility you could always add a first function to the Array.protoype:
Array.prototype.first = function () {
return this[0];
};
A then you could easily retrieve the first element:
[1, 2, 3].first();
> 1
If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find():
var elements = []
elements[1] = 'foo'
elements[2] = 'bar'
var first = function(element) { return !!element }
var gotcha = elements.find(first)
console.log(a[0]) // undefined
console.log(gotcha) // 'foo'
array.find(e => !!e); // return the first element
since "find" return the first element that matches the filter && !!e match any element.
Note This works only when the first element is not a "Falsy" : null, false, NaN, "", 0, undefined
In ES2015 and above, using array destructuring:
const arr = [42, 555, 666, 777]
const [first] = arr
console.log(first)
Only in case you are using underscore.js (http://underscorejs.org/) you can do:
_.first(your_array);
I know that people which come from other languages to JavaScript, looking for something like head() or first() to get the first element of an array, but how you can do that?
Imagine you have the array below:
const arr = [1, 2, 3, 4, 5];
In JavaScript, you can simply do:
const first = arr[0];
or a neater, newer way is:
const [first] = arr;
But you can also simply write a function like...
function first(arr) {
if(!Array.isArray(arr)) return;
return arr[0];
}
If using underscore, there are list of functions doing the same thing you looking for:
_.first
_.head
_.take
ES6 Spread operator + .shift() solution
Using myArray.shift() you can get the 1st element of the array, but .shift() will modify the original array, so to avoid this, first you can create a copy of the array with [...myArray] and then apply the .shift() to this copy:
var myArray = ['first', 'second', 'third', 'fourth', 'fifth'];
var first = [...myArray].shift();
console.log(first);
Try alert(ary[0]);.
I prefer to use Array Destructuring
const [first, second, third] = ["Laide", "Gabriel", "Jets"];
console.log(first); // Output: Laide
console.log(second); // Output: Gabriel
console.log(third); // Output: Jets
Method that works with arrays, and it works with objects too (beware, objects don't have a guaranteed order!).
I prefer this method the most, because original array is not modified.
// In case of array
var arr = [];
arr[3] = 'first';
arr[7] = 'last';
var firstElement;
for(var i in arr){
firstElement = arr[i];
break;
}
console.log(firstElement); // "first"
// In case of object
var obj = {
first: 'first',
last: 'last',
};
var firstElement;
for(var i in obj){
firstElement = obj[i];
break;
}
console.log(firstElement) // First;
Just use ary.slice(0,1).pop();
In
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log("1º "+ary.slice(0,1).pop());
console.log("2º "+ary.slice(0,2).pop());
console.log("3º "+ary.slice(0,3).pop());
console.log("4º "+ary.slice(0,4).pop());
console.log("5º "+ary.slice(0,5).pop());
console.log("Last "+ary.slice(-1).pop());
array.slice(START,END).pop();
Another one for those only concerned with truthy elements
ary.find(Boolean);
Find the first element in an array using a filter:
In typescript:
function first<T>(arr: T[], filter: (v: T) => boolean): T {
let result: T;
return arr.some(v => { result = v; return filter(v); }) ? result : undefined;
}
In plain javascript:
function first(arr, filter) {
var result;
return arr.some(function (v) { result = v; return filter(v); }) ? result : undefined;
}
And similarly, indexOf:
In typescript:
function indexOf<T>(arr: T[], filter: (v: T) => boolean): number {
let result: number;
return arr.some((v, i) => { result = i; return filter(v); }) ? result : undefined;
}
In plain javascript:
function indexOf(arr, filter) {
var result;
return arr.some(function (v, i) { result = i; return filter(v); }) ? result : undefined;
}
Why not account for times your array might be empty?
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
first = (array) => array.length ? array[0] : 'no items';
first(ary)
// output: first
var ary = [];
first(ary)
// output: no items
When there are multiple matches, JQuery's .first() is used for fetching the first DOM element that matched the css selector given to jquery.
You don't need jQuery to manipulate javascript arrays.
You could also use .get(0):
alert($(ary).first().get(0));
To get the first element of the array.
Declare a prototype to get first array element as:
Array.prototype.first = function () {
return this[0];
};
Then use it as:
var array = [0, 1, 2, 3];
var first = array.first();
var _first = [0, 1, 2, 3].first();
Or simply (:
first = array[0];
The previous examples work well when the array index begins at zero. thomax's answer did not rely on the index starting at zero, but relied on Array.prototype.find to which I did not have access. The following solution using jQuery $.each worked well in my case.
let haystack = {100: 'first', 150: 'second'},
found = null;
$.each(haystack, function( index, value ) {
found = value; // Save the first array element for later.
return false; // Immediately stop the $.each loop after the first array element.
});
console.log(found); // Prints 'first'.
try
var array= ['first', 'second', 'third', 'fourth', 'fifth'];
firstElement = array[array.length - array.length];
https://playcode.io/908187
A vanilla JS code, no jQuery, no libs, no-nothing.. :P.. It will work if array index does not start at zero as well.
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.values(ary)[0]);
If you're chaining a view functions to the array e.g.
array.map(i => i+1).filter(i => i > 3)
And want the first element after these functions you can simply add a .shift() it doesn't modify the original array, its a nicer way then array.map(i => i+1).filter(=> i > 3)[0]
If you want the first element of an array without modifying the original you can use array[0] or array.map(n=>n).shift() (without the map you will modify the original. In this case btw i would suggest the ..[0] version.
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.keys(ary)[0]);
Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.
var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first
cosnole.log(ary);
// ["second", "third", "fourth", "fifth"]
#NicoLwk You should remove elements with splice, that will shift your array back. So:
var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}

TS map list of string dates to list of string years

I have a list of dates in string format, like this:
0: "2020-07-10T00:00:00"
1: "1999-01-01T00:00:00"
2: "2020-06-16T00:00:00"
I need to map it in such a way, so I will have a list of year strings- like this:
0: "2020"
1: "1999"
2: "2020"
My way of thinking is trimming the start of the string, then appending it to the new list of years.
What is the most efficient way to do this?
I would use map to transform your given array. Each element needs to be split by - and then use substr(0, 4) to get the first 4 chars, which are the year.
const myArr = ["2020-07-10T00:00:00", "1999-01-01T00:00:00", "2020-06-16T00:00:00"];
const result = myArr.map(v => v.substr(0, 4));
console.log(result)
Use the Date#getFullYear method.
["2020-07-10T00:00:00", "1999-01-01T00:00:00", "2020-06-16T00:00:00"]
.map(date => new Date(date).getFullYear())

How prevent Object.keys() sort?

The problem with the ECMA standard for sort of Object.keys() is known:
Object.keys() handle all keys with integer (example: 168), including integer as strings (example: "168"), as a integer. The result is, both are the same (168 === "168"), and overwrite itself.
var object = {};
object["168"] = 'x';
object[168] = 'y';
Object.keys(object); // Array [ "168" ]
object[Object.keys(object)]; // "y"
Interestingly, all keys (including pure integer keys) are returned as a string.
The ecma262 wrote about this: All keys will be handle as a integer, expect the key is a String but is not an array index.
https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
That should tell us: 168 === "168". A toString() do not solve the problem.
var object = {};
object[[3].toString()] = 'z';
object[[1].toString()] = 'x';
object[[2].toString()] = 'y';
Object.keys(object);
// Array(3) [ "1", "2", "3" ]
Paradoxically, in this case, only integer apply as "enumerable" (it's ignoring array.sort(), that sort also strings with letters.).
My question about this is simple: How can i prevent the sort function in Object.keys()? I have testet the Object.defineProperties(object, 1, {value: "a", enumerable: true/false}), but that mean not realy enumerable in the case of integer or string or integer-like string. It means only should it be counted with or not. It means "counted" like omit (if it false), not "enumerabled" like ascending or descending.
A answere like that is not a good answer: Please use only letters [a-zA-Z] or leastwise a letter at the first position of keyword.
What I want: That the keys are not sorted, but output in the order in which they were entered, whether integer, string or symbol.
Disclaimer: Please solutions only in JavaScript.
Javascript Objects are unordered by their nature. If you need an ordered object-like variable I would suggest using a map.
To achieve what you're looking for with a map instead of object you'd do something like the below:
var map1 = new Map();
map1.set("123", "c");
map1.set(123, "b");
var iterator1 = map1.keys();
var myarray = [];
for (var i = 0; i < map1.size; i++) {
myarray.push(iterator1.next().value);
}
console.log(myarray);
// Array ["123", 123]
Unfortunately it's not compatible with IE and I'm not sure how else you could achieve what you need without it. A quick Google did return something about jQuery maps, though.
If you don't want to use jQuery and still need to support IE some points are below:
Is there anything stopping you using an array rather than JS object to store the data you need? This will retain the order per your requirements unlike objects. You could have an object entry in each iteration which represents the key then use a traditional foreach to obtain them as an array. I.e.
The array:
var test_array = [
{key: 123, value: 'a value here'},
{key: "123", value: 'another value here'}
];
// console.log(test_array);
Getting the keys:
var test_array_keys = [];
test_array.forEach(function(obj) { test_array_keys.push(obj['key']); } );
// console.log(test_array_keys);
Then if you needed to check whether the key exists before adding a new entry (to prevent duplicates) you could do:
function key_exists(key, array)
{
return array.indexOf(key) !== -1;
}
if(key_exists('12345', test_array_keys))
{
// won't get here, this is just for example
console.log('Key 12345 exists in array');
}
else if(key_exists('123', test_array_keys))
{
console.log('Key 123 exists in array');
}
Would that work? If not then the only other suggestion would be keeping a separate array alongside the object which tracks the keys and is updated when an entry is added or removed to/from the object.
Object Keys sorted and store in array
First Creating student Object. then sort by key in object,last keys to store in array
const student={tamil:100, english:55, sci:85,soc:57}
const sortobj =Object.fromEntries(Object.entries(student).sort())
console.log(Object.keys(sortobj))
use map instead of an object.
let map = new Map()
map.set("a", 5)
map.set("d", 6)
map.set("b", 12)
to sort the keys (for example, to update a chart data)
let newMap = new Map([...map.entries()].sort())
let keys = Array.from(newMap.keys()) // ['a','b','d']
let values = Array.from(newMap.values()) // [5,12,6]

How to map an array of integers as keys to dictionary values

If I have the following array and I want to create a string array containing the door prizes by mapping the mysteryDoors array as keys for the dictionary, and get the corresponding values into a new array.
Thus I would get a string array of ["Gift Card", "Car", "Vacation"] how can I do that?
let mysteryDoors = [3,1,2]
let doorPrizes = [
1:"Car", 2: "Vacation", 3: "Gift card"]
You can map() each array element to the corresponding value in
the dictionary. If it is guaranteed that all array elements are
present as keys in the dictionary then you can do:
let mysteryDoors = [3, 1, 2]
let doorPrizes = [ 1:"Car", 2: "Vacation", 3: "Gift card"]
let prizes = mysteryDoors.map { doorPrizes[$0]! }
print(prizes) // ["Gift card", "Car", "Vacation"]
To avoid a runtime crash if a key is not present, use
let prizes = mysteryDoors.flatMap { doorPrizes[$0] }
to ignore unknown keys, or
let prizes = mysteryDoors.map { doorPrizes[$0] ?? "" }
to map unknown keys to a default string.
If you have to use map, then it would look something like the following:
let array = mysteryDoors.map { doorPrizes[$0] }
After re-reading the Apple Doc example code and changing it to what I need. I believe this is it (Almost). Unfortunately it is now in string format with new lines...
let myPrizes = doorPrizes.map { (number) -> String in
var output = ""
output = mysteryDoors[number]!
return output;
}

Finding and matching two strings in different arrays

I'm trying to pass two arguments into a script that looks through arrays with a lot of values.
Basically, I have a pretty big JSON file with around 15 arrays (google sheet data). I then want to take the 1st argument, which is one/multiple words and match it in the 1st array. And then I want to take index numbers in the 1st array and only look through those index numbers in the 2nd array for a string that matches the 2nd argument and return the strings and the index number for future use. For example:
sheetData = [ [ "1stArray", "other", "other" ], [ "2ndArray", "stuff", "2stuff", "stuff" "2stuff" ] ]
If I then would type in: node index.js other 2stuff. It is supposed to find the two "other" entries in the 1st array, then look at the "stuff" and the first "2stuff" in the 2nd array and then return both "2stuff" and the index number 2.
So far I've been able to find one of the strings matching the 1st argument in the 1st array, but not the other ones. Nor have I been able to even go through the 2nd array trying to find another string. Here is the code I've written so far for this:
let fs = {
help: config.help.failstack,
func: (client, message, args) => {
// E = Enhance, R = Repair/replace, D = re-enhance (degrade part),
let itemName = args[0];
let enhanceWanted = args[1];
debugger;
var a = sheetData.values[[0]];
var sheetItemName = a.indexOf(itemName);
if (sheetItemName === -1) {
message.reply('Command not formatted correctly.')
.then(msg => console.log())
.catch(console.error);
} else {
var sheetFailstack = a.indexOf(enhanceWanted);
message.reply()
.then(msg => console.log(`${msg}`))
.catch(console.error);
}
}
}
var sheetFailstack = a.indexOf[enhanceWanted];
should be:
var sheetFailstack = a.indexOf(enhanceWanted);

Resources