Comparing array value with object - javascript

Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.
E.g.
a = [1,2,3,4,5];
b = [{1:group1},{2:group2},{3:group3}];
If id in a matches id in b then print out the id's group value
var a = [];
var b = [];
var c = {};
if (condition) {
c = {id:group}
b.push(c)
}
if (condition) {
a.push(id)
}
for (var i = 0; i < a.length; i++) {
//If id value in a exists in b, get id's corresponding group value from b
}

function find() {
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
if (b[j].hasOwnProperty(a[i])) {
return b[j][a[i]];
}
}
}
}

An alternative solution:
<script>
a = [
1, // index 0
2, // index 1
3, // index 2
4, // index 3
5 // index 4
];
b = [
{1:'group1'}, // index [0][1]
{2:'group2'}, // index [1][2]
{3:'group3'} // index [2][3]
];
// If id in a matches id in b then print out the id's group value
var i = 1;
for (var key in b) {
var bKeys = Object.keys(b[key]);
if(bKeys[0] == a[key]) {
console.log(b[key][i]);
}
i++;
}
</script>

Related

remove specified value from array [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 1 year ago.
How can I check whether an array contains a value, and if so, remove it?
PS: For this exercise, I'm not allowed to use anything more than than .pop, .push and .length array functions.
My logic is the following: if the specified value is within the array, reorder the array so that the last element of it will contain this value, then remove it with .pop. But how can I find this value and reorder it without using anything more than those array functions I specified above?
This is what I managed to come up with so far:
let array_1 = [1,2,3];
if (array_1 == 2){
//reorder somehow
array_1.pop();
}
console.log(array_1);
Using this approach, you are not creating a new array but modifying it. It uses .pop().
let array_1 = [1, 2, 3];
// Iterate all array
for (let i = 0; i < array_1.length; i++) {
// While there is a 2 element in the actual index, move all elements (from i index) to the previous index
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
// Now remove the last element (since we move all elements to the previous index)
array_1.pop();
}
}
console.log(array_1);
Here a snippet so you can try it
let array_1 = [1, 2, 3, 4, 2, 5, 2, 6, 2];
for (let i = 0; i < array_1.length; i++) {
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
array_1.pop();
}
}
console.log(array_1);
This would mantain the order of the array, but without the "2" elements.
Here's another option using pop
const filter = (array, target) => {
const newArray = [];
let tmp;
while(tmp = array.pop()) {
if (tmp !== target) {
newArray.push(tmp)
}
}
console.log(newArray)
return newArray;
}
filter([1,2,3,4], 2) // [4, 3, 1] Note that it reversed the order of the array!
If you are limited to pop, push and length, you can loop over all elements, check if a given element matches the value you are looking for, and add them to a new array using push.
let array_1 = [1,2,3];
let newArray = [];
for (let i = 0; i < array_1.length; i++) {
if (array_1[i] !== 2) {
newArray.push(array_1[i]);
}
}
console.log(newArray);
// using splice
// splice(indexStart, how many, replace with)
// example :
let arr = [0,1,2,3,4,5];
// remove at index 1
arr.splice(1,1);
console.log( arr );
// replace at index 1
arr.splice(1,1,"new 1");
console.log( arr );
// merge index 2 and 3
arr.splice(2,2,"merge 2 and 3");
console.log( arr );
// create 2 new items start at index 2
arr.splice(2,2,"new 2", "new 3");
console.log( arr );

JavaScript: How to get two elements in a array to equal any given number

My question is:
If I have a array like this,
example:
var myArray = [1,2,4,6,9]
and I want to get the number 15 by getting (adding) the index of 6 and 9.
How do I do that?
I can't make it work and I have tried endlessly... please help.
My attempt:
var list = [1,3,5,7,9];
function sumOfIndex(list , weight) {
weight = [];
for (i = 0; i < list.length; i++) {
for (j = 0; j < list[i].length; j++) {
list.push(weight);
}
}
}
In the array from your example, the index of 6 is [3] and the index of 9 is [4].
Simply add them together and you have 15.
Run the snippet below:
var myArray = [1,2,4,6,9]
console.log(myArray[3] + myArray[4])
I'd go over the array and create a map from the complement of each element to its index:
function findSum (arr, sum) {
const diffs = new Map();
for (let i = 0; i < arr.length; ++i) {
if (diffs.has(arr[i])) {
return [diffs.get(arr[i]), i];
}
diffs.set(sum - arr[i], i);
}
}

js how to make 2d array matrix with for loop and continue counting numbers on next row

I'm trying to make my 2d matrix to have numbers which continue on the new row
var myMatrix = [];
var row = 5;
var colom = 3;
for (var i = 0; i < rows; i++) {
var toto = 1;
myMatrix[i] = [i];
for (var j = 0; j < colom; j++) {
myMatrix[i][j] = [i + j];
}
}
console.log(myMatrix);
I'm trying to make it print numbers like this:
123
456
789 and etc...
but without success:/
can someone help and also give a video or site with examples where i can learn more about that kind of stuff?
First, a look at what your code is doing:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [i];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = [i+j];
}
}
console.log(myMatrix);
You have a typo in your row/rows variable name. Ignoring that though...
Your myMatrix[i] line is creating an array at i, which is then being set to an array with a value of i. Just this creates a wonky mash-up , where each "row" gets an array with it's row number as the first value, something like this:
[[0], [1], [2], [3], [4]]
Your inner loop then adds a value to that array at the place and adds i+j together, but puts that inside of an array, which isn't what you want, so you get something like this:
[
[[0], [1], [2]], // i = 0
[[1], [2], [3]], // i = 1
[[2], [3], [4]], // i = 2
// ... etc
]
Also note that you are replacing that first [i] anyways, so don't set it like that, just make it an empty array [].
What you want is something like this:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j;
}
}
console.log(myMatrix);
There were three changes to your code:
Make the [i] and []. It doesn't hurt anything, but [i] also doesn't make sense.
Take the i+j part out of the array, you just want a value there.
When you add i, multiply it by columns so it doesn't reset every time: (i*columns)+j
This will give you a nice output, starting with 0. If you want it start at 1, just add one to your value:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j+1;
}
}
console.log(myMatrix);
Use i * columns + j ... and I have to add up to 30 chars for padding

How to get even numbers array to print first instead of odds?

So I have this function where I've need to take out the evens and odds and put them into separate arrays but I need the evens array to print first rather than the odds.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[i & 1].push(numbersArray[i]);
}
return evensOdds;
}
If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
If you want to split them by even and odd indexes use (i + 1) % 2 to determine the sub array to push into:
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[(i + 1) % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
Just for fun, a forEach version of the accepted answer.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var even_odd = [ [], [] ];
numbersArray.forEach( e => even_odd[e%2].push(e) );
console.log(even_odd);

Javascript. access property by string

I have a function that takes two lists(each item in the two lists are the same type). It only adds item from the second list to the first list if the item in the second list does not exist in the first list. To determine if it exist in the list, I compare the property pk.
addUniqueItemsToList: function (sourceList, toAddList) {
for (var a = 0; a < toAddList.length; a++) {
var doesItemExist = false;
for (var b = 0; b < sourceList.length; b++) {
if (sourceList[b].pk == toAddList[a].pk) {
doesItemExist = true;
break;
}
}
if (!doesItemExist) {
sourceList.push(toAddList[a]);
}
}
}
Is there a way in javascript where instead of comparing pk, I can compare it to other properties of the object, by passing in the name of the property to the function? i.e., addUniqueItemsToList: function (sourceList, toAddList, propertyName)
Yes you can compare by object property directly and access properties dinamically using string as key ej array['mykey']. Also it would be better if instead of doing a for inside a for (1for - n for) create a map in order to avoid so much iterations:
Eg: Number iterations without a map when items.length = 100 & anotherItems.length = 200
100*200 = 20000 possibles iterations.
Eg. Number of iterations creating a map with items.length = 100 & anotherItems.length = 200
300 iterations.
Example of how i do it:
var items = [{_id: 1, text: "Text 1"}, {_id:2, text: "Text 2"}];
var anotherItems = [{_id: 1, text: "Text 1"}];
var mapByProperty = function(array, prop) {
var map = [];
for (var i = 0, len = array.length; i !== len; i++) {
map[array[i][prop]] = array[i];
}
return map;
};
var commonUniqueProperty = '_id';
var mappedAnotherItemsById = mapByProperty(anotherItems, commonUniqueProperty);
for(var i = 0, len = items.length; i !== len; i++) {
if(mappedAnotherItemsById[items[i][commonUniqueProperty]]) {
console.log(items[i]);
}
}

Categories