Javascript Access Two-Dimensional Array - javascript

I have the following array
var array = [["ABC", "123"], ["DEF", "456"];
How can I get "123", if I look for "ABC?
I tried
array["ABC"][1] //Want Output: 123
array["DEF"][1] //Want Output: 456

You can use Array#find.
var array = [["ABC", "123"], ["DEF", "456"]];
let abc = array.find(x=>x[0]==="ABC");
console.log(abc?.[1]);
let def = array.find(x=>x[0]==="DEF");
console.log(def?.[1]);
let nothing = array.find(x=>x[0]==="NOTHING");
console.log(nothing?.[1]);
However, using an object or Map is much better suited to this purpose. You can convert your array to an object using Object.fromEntries.
var array = [["ABC", "123"], ["DEF", "456"]];
const obj = Object.fromEntries(array);
console.log(obj.ABC);
console.log(obj['DEF']);
You can pass the array to the Map constructor as well. Maps are better if you always want to retain insertion order.
var array = [["ABC", "123"], ["DEF", "456"]];
const map = new Map(array);
console.log(map.get("ABC"));
console.log(map.get("DEF"));

You can use find to locate the item with the value at index 0. If you found, return the value at index 1.
const findByFirstValue = (arr, val) =>
((res) => res ? res[1] : null)(arr.find(v => v[0] === val))
console.log(findByFirstValue([["ABC", "123"], ["DEF", "456"]], 'ABC'))
.as-console-wrapper { top: 0; max-height: 100% !important; }

You can use map
const array = [["ABC", "123"], ["DEF", "456"]];
const newMap = new Map();
array.map(item=>{
newMap[item[0]] = item;
})
console.log(newMap['ABC'][1]);

what you are trying to do is impossible using array, you are not allowed to use:
array["ABC"]
since array's indexing is number based, you need to use objects in order to get what you want:
var array = {"ABC": ["123", "789"], "DEF": ["456", "323"]};
now you are able to select them as you want:
array['ABC'][1] // 123

you can use index to get a value from array in
//first level
// array[0] =>["ABC", "123"]
// array[1] => ["DEF", "456"]
//second level
// array[0][0]=> "ABC"
// array[0][1]=> "123"
also you can use methods like map
or foreach

Related

From an array, find the array that has the true values for the objects

Given array:
const array = [{1: true},{2: false},{3: true},{}.....];
Filter the given array by only including objects with values of true.
Looking for the shortest solution.
const onlyTrue = array.filter((el, ind) => el[ind + 1] === true);
This will work only if indexes in array objects are ordered and starting from 1, as it is in your example.
Assumptions (based on what's in your example):
Each object in the array only has at least 1 property in it
The first property on each object is the one we care about
The property in each object is different every time
const array = [{1: true},{2: false},{3: true}];
const results = array.filter(item => Object.values(item)[0]);
If you want to avoid any false positives from truth-y values (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy), then change the filter call to this instead:
const results = array.filter(item => Object.values(item)[0] === true);
const array = [{1: true},{2: false},{3: true}];
const array2 = [];
array.forEach(filterTrue);
function filterTrue(item){
for(x in item){
if(item[x]===true){
array2.push(item);
}
}
}
console.log(array2);
Hope this helps you.

Convert Array of arrays of objects to Array of Arrays

I have to following array:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
And I would like to convert it to an array of arrays, as follows:
var arr1 = [
["0.1","0"],
["1.1","1"],
["2.1","2"]
];
I would like to convert to the other array only a few properties, not all of them.
Any idea how I can do this?
PS: I was using flatMap from another post but it does not work as it does not exist in Edge.
Assuming that the second value in each subarray is coming from the number after the period from the m key, you could use the map function to accomplish this:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
var newArray = arr1.map(x => [x[0].n, x[0].m.split('.')[1]]);
console.log(newArray);
For next time you have to put your attempts.
this is the solution for your problem
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
arr1 = arr1.map(currentArray=>{
const item = currentArray.shift();
return [item.n,item.m.replace( /^\D+/g, '')]
});

Find unique words from an array of anagrams using Map in Javascript

I know how to do it without Map. It seems more logical to use Map for this task but I can't seem to implement it. Is this even possible?
So far I tied this:
function aclean(arr) {
let result = [];
let unique = new Map();
for(let i = 0; i < arr.length; i++){
let sorted = arr[i].toLowerCase().split("").sort().join("");
/*if (unique.add(sorted)) {
result.push(arr[i]);
}*/
}
return result;
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
The result should be: nap,teachers,ear or PAN,cheaters,era
You could loop over your array using .forEach(), and check at each iteration whether or not your Map has a key of the sorted word, if it doesn't, then you set the sorted word as the key, and the word associated with the word as the value. You can then return an array of your map's .values() to get your result:
function aclean(arr) {
let unique = new Map();
arr.forEach(word => {
let sorted = word.toLowerCase().split("").sort().join("");
if(!unique.has(sorted)) {
unique.set(sorted, word);
}
});
return [...unique.values()];
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
You could take a Set with the normalized (lower case, sorted) strings and return a filtered result.
function aclean(array) {
let unique = new Set();
return array.filter(s => {
let sorted = s.toLowerCase().split("").sort().join("");
if (!unique.has(sorted)) {
unique.add(sorted);
return true;
}
});
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
I think Set is prefect for this case. You can do it in following steps.
First make a helper function which sorts to the strings.
Then create a unique array of sorted strings using Set and map()
Then map() that array again to the value in original array which is anagram of the sorted string.
const sort = str => str.toLowerCase().split('').sort().join('')
const aclean = arr => [... new Set(arr.map(sort))].map(x => arr.find(a => sort(a) === x))
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));

Search through multidimensional Javascript array

I have an array set up like the following:
var array = [["A1", "left:81px"], ["A2", "left:145px"],...]
The purpose of this is to take a user input and search through this array to find the location to move an element to. If the user input is "A1" how can I parse through this array to set some variable equal to "left:81px"?
Use find and some simple destructuring.
var array = [
["A1", "left:81px"],
["A2", "left:145px"]
];
const [, res] = array.find(([k]) => k == "A1") || [];
console.log(res);
The above returns undefined if no value is found.
Slightly simpler code:
var array = [
["A1", "left:81px"],
["A2", "left:145px"]
];
const input = "A1";
let res = "";
for (let i = 0; i < array.length; i++) {
if (array[i][0] == input) {
res = array[i][1];
break;
}
}
console.log(res);
Assuming that the inner arrays are always structured like [key, value]:
// this is your array.
const array = [["A1", "left:81px"], ["A2", "left:145px"]]
// user input:
const query = "A1";
// find an inner array in array whose first element matches the user input
const [, result] = array.find(([key]) => key === query) || []
console.log(result);
If possible, you should use a better (map-like) data structure for this:
const data = {
A1: 'left:81px',
A2: 'left:145px'
};
const query = 'A1';
const result = data[query];
console.log(result);
The array version has a linear runtime where as the second one is constant time. If you will do this lookup often, it is worth converting your array representation to an object
To achieve expected result, use Object.fromEntries to convert key ,value pair array to object - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
Convert key-value pairs array to object using Object.fromEntries.
Find value using key value like A1,A2
working code sample
var arr = [["A1", "left:81px"], ["A2", "left:145px"]]
function findVal(word, arr){
var obj = Object.fromEntries(arr)
return obj[word]
}
console.log(findVal('A1', arr))
Option 2: Using reduce and converting key ,value pair array to object one time and use for further searches everytime and also for better browser compatibility compare to Object.fromEntries
var arr = [["A1", "left:81px"], ["A2", "left:145px"]]
var obj = arr.reduce((acc,v)=>{
acc[v[0]] = v[1]
return acc
}, {})
console.log(obj['A1'])

How to get the matching second array of object in es6

I have two array of objects: - better solution
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
Expected output be:
if first array and second array id matches means take the second array name
in above example id 2 matches and we need id:2,name: panasonics.
o/p:
[{id:1,name:"samsung"},{id:2,name:"panasonics"},{id:3,name:"Lg"},{id:5,name:"samsung"},{id:7,name:"Apple"}]
Combine the arrays using Array.concat(), reduce them into a Map by id, and then convert the Map's values to an array with Array.from():
const unionBy = (field, ...arrays) => Array.from(
[].concat(...arrays)
.reduce((r, o) => r.set(o.id, o), new Map)
.values()
);
const array1 = [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
const result = unionBy('id', array1, array2);
console.log(result);
You can use a simple .forEach() loop like below (you can also use a for loop if you want, but .forEach() is easier).
This code loops through array1, and loops through array2 in that loop. It then checks if the ids are the same. If there are, the name is appended to result.
const array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
let result = [];
array1.forEach(e1 => {
array2.forEach(e2 => {
if (e1.id == e2.id) {
result.push(e2.name);
}
});
});
console.log(result);
Use map() and concat() like the following code
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"}, {id:2,name:"panasonics"},{id:7,name:"Lg"}];
var array3=array1.map(function(i,v){
if(array2[v].id==i.id){
return array2[v]
}
else return i
})
array4=array3.concat(array2);
console.log(array4);

Categories