Find item between row and column in JavaScript - javascript

I want to find what's the position of the following array, according to the table below.
So, here is an example:
I have this array : ['AA','CC','TC']
and I have this table:
Now, according to the array, my first value is 'AA'. So if you notice, we have A and A as the fist index, which we have to read in the table below. So first, we look in the rows of the table, and then we check the columns. we see, that the number of the row and of the columns in the value:12.
So far I have this code in JavaScript:
function cal_extinction_coefficient(str) {
var values_compare= [['Values', 'A','C','T'], ['A', 12,14,16], ['C',23,25,26], ['T',31,34,37]];
var values_to_find=['AA','CC','TC']
let chunk=0;
var all_combLength= values_to_find.length;
for (var i = 0; i < all_combLength; i++) {
for (let j = 0; j < values_compare.length; j++) {
const final= times[j].includes(all_combinations[i].slice(0,1));
}
}
However, I don't know how to access these values... I have the same resolution, but in pandas and with python...
Can someone help me please?

If you are new to JS, try to create your own functions first. It's usually easier than it seems to be.
const data = {
dataFrame: [
['A', 27, 21],
['C', 21, 14]
],
columns: ['Type', 'A','C']
}
const getValue = (xy) => {
[col, row] = xy.split('');
return data.dataFrame.find(x => x[0] == row)?.[data.columns.indexOf(col)];
}
console.log(getValue("AA"));

You could use nested objects:
const type1 = {A: {A: 27, C: 21}, C: {A: 21, C: 14}}
and access your elements with
type1['A']['C']
or
type1.A.C
Using lodash#get you can access the element with
_.get(type1, ['A', 'C'])
Examples:
const type1 = {A: {A: 27, C: 21}, C: {A: 21, C: 14}};
console.log(type1['A']['C']);
console.log(type1.A.C);
console.log(_.get(type1, ['A', 'C']));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

Related

In Javascript, given key/value pairs, return values from array of keys

const pairs = { a : 1, b : 2, c : 3 }
const keyArray = [a, b, c]
I'm trying to get a function or w/e that returns [1, 2, 3]. can't think of anything please help
In javascript all keys of an object are actually strings, and can be addressed using the same strings.
Your code is creating an array containing the values of the - possibly uninitialized - variables a, b and c, which then produces [undefined, undefined, undefined], or else whatever those variables contain.
You need to make keyArray contain strings instead, and then you can use the map() function to produce the desired result:
const pairs = { "a" : 1, "b" : 2, "c": 3 }
const keyArray = ["a", "b", "c"]
const values = keyArray.map(key => pairs[key]);
console.log(values);
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
const keyArray = ['a', 'b', 'c']
for(const item of keyArray)
{
console.log(pairs[item])
}
You need to make your items inside the array and object as strings
Well since it's Javascript
Object.values() should do it.
const keyArray = Object.values(pairs)
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
for(const [key , value] of Object.entries(pairs))
{
console.log(key) // a , b, c
console.log(value) // 1, 2, 3
}

Adding an Array Value as a Javascript Object Property

function select(arr, obj) {
var myKeys = Object.keys(obj);
var myValues = Object.values(obj);
var newObj = {};
for(var i=0; i<myKeys.length; i++) {
if(arr[i] === myKeys[i]) {
newObj[myKeys[i]] = myValues[i];
}
}
return newObj;
}
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
/*
If keys are present in the given array, but are not in
the given object, it should ignore them.
It does not modify the passed in object.
*/
I'm having trouble adding an array as an object property. I created a new Object to store the values in, however it only stores the first instance of arr[i]. I'm confused at this point any help?
Do this instead
for(var i=0; i<arr.length; i++) {
if(myKeys[arr[i]] !== undefined) {
newObj[arr[i]] = myValues[i];
}
}
Your code works only if the index of matching keys is exactly the same.
The problem in your code is that it assumes that the ith value in the array must correspond to the ith key of the object, but that order is not guaranteed.
Here is a functional programming style solution, that uses Obect.fromEntries to construct the returned object:
const select = (arr, obj) =>
Object.fromEntries(arr.filter(key => key in obj).map(key => [key, obj[key]]));
var arr = ['a', 'c', 'e'];
var obj = {a: 1,b: 2,c: 3,d: 4};
var output = select(arr, obj);
console.log(output);
I'd use the relatively recently added Object.fromEntries to create an object directly from a map of a filtered set of keys from your object.
function select (arr, obj) {
// get the keys from obj and filter to those present in arr
var keys = Object.keys(obj).filter(key => arr.includes(key));
// create an array of arrays where each inner array has a key and value
var entries = keys.map(key => [key, obj[key]]);
// call fromEntries with that new array.
return Object.fromEntries(entries);
}
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
/*
If keys are present in the given array, but are not in
the given object, it should ignore them.
It does not modify the passed in object.
*/

Array of Objects ordered by similarity to neighbour

I really hope you can help me I have an array of objects and I need an algorithm or a pointer to something to read up on that will sort them by similarity to their neighbours.
For Example
[
{a:12,b: 7,c: 5},
{a: 5,b: 5,c: 5},
{a: 3,b: 3,c: 3},
{a: 5,b: 7,c: 5},
{a:12,b: 7,c: 5}
]
becomes
[
{a: 5,b: 5,c: 5},
{a: 5,b: 7,c: 5},
{a:12,b: 7,c: 5},
{a:12,b: 7,c: 5},
{a: 3,b: 3,c: 3},
]
I have a REPL here...
https://repl.it/#idrise/ThoseWellmadeMonitors
I have brute forced it but it doesn't get the best score and it takes eons on big arrays.
This is how the score is calculated, the higher the score the better !
function scoreArray(array) {
let score = 0;
for (let f = 1; f < array.length; f++) {
score += howSimilarAreObjects(array[f - 1], array[f]);
}
return score;
}
function howSimilarAreObjects(object1, object2) {
let score = 0;
Object.keys(object1).forEach(curValue => {
if (object1[curValue] === object2[curValue]) {
score++;
}
});
return score;
}
Any help greatly appreciated,
Idris
You could run every element against each other and get the similarity between the both objects. Then take the groups and get the objects with the highest similarity first and then with the lower ones. By pushing them to the result set, filter the array by already seen objects.
const similar = (a, b) => Object.keys(a).filter(k => a[k] === b[k]).length;
var array = [{ a: 12, b: 7, c: 5}, { a: 5, b: 5, c: 5}, { a: 3, b: 3, c: 3}, { a: 5, b: 7, c: 5}, { a: 12, b: 7, c: 5}],
groups = {},
used = new Set,
result = [];
array.forEach((a, i) =>
array
.slice(i + 1)
.forEach(b => (s => (groups[s] = groups[s] || []).push(a, b))(similar(a, b))));
Object
.keys(groups)
.reverse()
.forEach(k => result.push(...groups[k].filter(o => !used.has(o) && used.add(o))));
console.log(result);
console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Let us define a function that you wish to minimize:
minimal sum of squared distance between every pair of neighbors
If you were to iterate over all n! permutations, and choose the lowest total, you would have achieved your goal. Of course, n! is way too expensive, so we have to use something simpler.
You can take a greedy approximation, which is simply:
start by any neighbor
continue with the nearest neighbor to the last-added one
repeat 2 until you finish
This will not be optimal, but will not be too far off either. And it is quite cheap to calculate (O(n^2), intead of O(n!)).
Using this function, you are essentially trying to solve the traveling salesman problem (TSP), on which a lot has been written, and for which a lot of approximations exist. The general problem is np-hard, so the normal approach is to choose a not-so-expensive approximation, of which the simplest may be the greedy approach outlined above.

Filter array of objects using a list of desired key values

I have an array of objects that might look like this:
var arr = [{
a: 1,
b: 321,
c: 556,
d: 8
}, {
a: 1,
b: 22,
c: 21,
d: 8
}, {
a: 1,
b: 1,
c: 43,
d: 8
}, ];
and another list that could be:
var list = ['a', 'c', 'd'];
Since my list only has keys a, c, and d I want to get rid of all instances of the b key on my original array. All this procedure has to be dynamic though because There is no way for me to know what those keys might be prior to receiving them.
Is there a nice and clean way of doing this in JavaScript?
arr.forEach(function(element)
{
for(var key in element)
{
if(list.indexOf(key) === -1)
{
delete element[key];
}
}
});
Should be pretty self-explanatory.
If you don't want to modify the original array:
arr.map(function(element)
{
element = JSON.parse(JSON.stringify(element));
for(var key in element)
{
if(list.indexOf(key) === -1)
{
delete element[key];
}
}
return element;
});
Consider using the underscore.js library. It contains a reject method that should do the trick
reject _.reject(list, predicate, [context])
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter.
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]
Is that what you're looking for?
for(var i=0, i < arr.length; i++) {
if(arr[i].b) delete arr[i].b
}
// Update, a vanilla approach
var reject = [ "b" ];
for(var i=0, i < arr.length; i++) {
for(var j in arr[i]) {
if(reject.indexOf(j) != -1) delete arr[i][j];
}
}

How to check an object contains a set of properties

I'll start this by saying, I understand there are many ways to do this. This question is an effort to compare different version.
I also understand we're looking for SO to be a QA site, not a QAAAAAAA... site.
So I'll refine the question to make it more focused and end up with one answer.
Given an object:
var obj = {a: 1, b: 2, c: 3};
Find out if the following keys are present:
var keys = ['a', 'b', 'c', 'd']; // 'd' would be flagged although a boolean would suffice
Ideally I'd like to do this in ES5, but ES6 is more than welcome.
Ideally without the use of lodash, but it's more than welcome.
I'm sure there's a lovely combination of the native Array methods that'll work:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
The aim is to have a function or line of code that's small and concise rather than something like:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
var found = keys.length;
for (var i = 0; i < keys.length; i++) {
if (obj.hasOwnProperty(keys[i])) {
found--;
}
}
console.log("Missing:", found);
I'll wade in with the first offering:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
var allPresent = Object.keys(obj).filter(function(item) {
return keys.indexOf(item) !== -1;
}).length === keys.length;
console.log("All present:", allPresent);
Like this:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
alert(keys.every(Object.prototype.hasOwnProperty, obj))
allPresent = keys.reduce(function ( acc, next ) {
return !acc || obj.hasOwnProperty(next);
}, true);
Although Amits answer is probably even smaller and preferred for browsers that support 'every'. (should be all of them by now)
Given object:
var obj = {a: 1, b: 2, c: 3},
keys = ['a','b'];
You can check if it contains key 'a' using this:
Object.keys( obj ).indexOf('a') !== -1
Thanks for comments here is full answer to check what OP requested for full equality:
JSON.stringify( Object.keys( obj ) ) === JSON.stringify( keys )
Or partial equality
JSON.stringify( Object.keys( obj ) ).indexOf( JSON.stringify( keys ) ) !== -1

Categories