How to add element in array if it was found? - javascript

I use this method to find object in array:
lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
arr.push(found);
Problem is that if element was not found it added this as undefined to array arr. How avoid this?
Why it does not find element with key: "subjectId":
let objKey = 7047;
let k = "subjectId";
let v = 7047;
found = this.obj[objKey].filter(item => item[k] == v);
console.log(found);// undefined

You can avoid this by checking the length found before you push it to the array.
lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
found.length > 0 && arr.push(...found);
I am using the spread syntax to push each element as its own item to the new array, which I assume that is what you want. You can remove the ... if you want all of the found items to be its own array item.

The function filter won't return undefined, will return an empty array instead (if none elements met the condition).
Problem is that if element was not found it added this as undefined to array arr.
You probably want to find a specific element, so, I recommend you to use the function find if you want only one object rather than an Array with only one index.
lat arr = [];
found = this.obj[objKey].find(item => item[internKeyName] == 7047);
if (found) arr.push(found);

You could push a spreaded array with the wanted objects directly, empty arrays are not spreaded (spread syntax ...).
arr.push(...this.obj[objKey].filter(item => item[internKeyName] == 7047));

Related

Get the object that has a certain number in it from an object within an object

I make an API call and it gives back the following:
[
[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],
[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],
[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164],
[1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598],
[1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030],
[1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208],
...
]
There are basically about 1000 objects in total, and every object has 7 objects within it, each of them containing the values shown above. Right now I have set
var objects= response.data.result[86400]
which gives the result you see above, and now, I need to search through these objects until Javascript finds the object that has the value '1529884800' in object zero, so for example with the code above this would result in this number:
object[5][0]
I wrote the following ode but it doesn't work, results in an empty array as response.
var results = [];
var toSearch = 1529539200;
for (var i=0; i<objects.length; i++) {
for (key in objects[i][0]) {
if (objects[i][key].indexOf(toSearch) != -1) {
results.push(objects[i]);
}
console.log(results)
}
}
(in the above results just shows [])
I tried doing var toSerach ='1529539200' and without quotes but neither work, what is the issue here? Would appreciate any help, thanks
If you want the index of a given number, use .flatMap() and .indexOf()
First iterate through the outer array
array.flatMap((sub, idx) =>
Then on each sub-array find the index of the given number. .indexOf() will either return the index of the number if it exists or -1 if it doesn't. In the final return it will be the index number of the sub-array and then the index of the number within the sub-array if found. Otherwise an empty array is returned which results in nothing because .flatMap() flattens arrays by one level.
sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : [])
const data = [[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164],[1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598],[1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030],[1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208]];
let A = 1529539200;
let B = 33036208;
let C = 15.16;
const findNumber = (array, number) =>
array.flatMap((sub, idx) =>
sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : [])
console.log(findNumber(data, A));
console.log(findNumber(data, B));
console.log(findNumber(data, C));

Puh array in empty array that create before

I push two Array in one Array But can't use them as a string,This result in bellow about two arrays in one array :
Array(0) [] //This is empty array that I create before and push these two array bellow to them
length:2
0:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
1:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
and I create a for for access them but I can ! I write this code "
for(var index = 0 ; index < Array.length ; ++index) {
let Each_String_In_Brackets = Array[index] ;
console.log(Each_String_In_Bruckets);
}
Why is this happen!
I mean Why when we push array in empty array can't access them!
I want to access the content of them, I have a string In each bracket.
var arr = [];
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
//assuming inside array always will be one element:
arr.forEach((item)=>{ console.log(item[0])})
//if inside array may be multiple elements, then use this
arr.forEach((item, index)=>{
item.forEach((child)=>{ console.log(child)})
})
pushing a full array into another array makes it a 2D array ( at the indexes where you push another array ) so for example if I have the first array
BArray[]
But if I push another array into it
BArray2 = [1,2,3,4];
BArray.push(Array2);
We would not be able to access it just by
BArray[0]
This would return the entire array2 rather the content of array2 at index 0.
Therefore you would do this
BArray[0][0]
So this would give us ( from your array ) "cfdb9868-0f69-5781-b1e4-793301280788"
If you would like to just dump out the content of BArray2 into BArray
You can use the spread operator.
BArray[...BArray2];
( Also I would not use Array as variable name ! It can be confusing as new Array(10); is a way of creating arrays and having arrays with that name isn't best practice ! )
Hope this helps !
You are pushing array in array, so you must access as 2D array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
array.push(arrayString1);
array.push(arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem[0]);
})
Or maybe you want to append array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
[].push.apply(array, arrayString1);
[].push.apply(array, arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem);
})

JavaScript - Filter array with mutation

I want to filter a array by keeping the same array without creating a new one.
with Array.filter() :
getFiltersConfig() {
return this.config.filter((topLevelConfig) => topLevelConfig.name !== 'origin')
}
what is the best way to get the same result by filtering by value without returning a new array ?
For completeness, I thought it might make sense to show a mutated array variant.
Below is a snippet with a simple function mutationFilter, this will filter the array directly, notice in this function the loop goes in reverse, this is a technique for deleting items with a mutated array.
Also a couple of tests to show how Array.filter creates a new array, and mutationFilter does not.
Although in most cases creating a new array with Array.filter is normally what you want. One advantage of using a mutated array, is that you can pass the array by reference, without you would need to wrap the array inside another object. Another advantage of course is memory, if your array was huge, inline filtering would take less memory.
let arr = ['a','b','a'];
let ref = arr; //keep reference of original arr
function mutationFilter(arr, cb) {
for (let l = arr.length - 1; l >= 0; l -= 1) {
if (!cb(arr[l])) arr.splice(l, 1);
}
}
const cond = x => x !== 'a';
const filtered = arr.filter(cond);
mutationFilter(arr, cond);
console.log(`ref === array -> ${ref === arr}`);
console.log(arr);
console.log(`ref === filtered -> ${ref === filtered}`);
console.log(filtered);
I want to filter a array by keeping the same array without creating a new one.
what is the best way to get the same result by filtering by value without returning a new array ?
I have an answer for the second criterion, but violates the first. I suspect that you may want to "not create a new one" specifically because you only want to preserve the reference to the array, not because you don't want to create a new array, necessarily (e.g. for memory concerns).
What you could do is create a temp array of what you want
var temp = this.config.filter((topLevelConfig) => topLevelConfig.name !== 'origin')
Then set the length of the original array to 0 and push.apply() the values "in-place"
this.config.length = 0; //clears the array
this.config.push.apply(this.config, temp); //adds what you want to the array of the same reference
You could define you custom method like so:
if(!Array.prototype.filterThis){
Array.prototype.filterThis = function (callBack){
if(typeof callBack !== 'function')
throw new TypeError('Argument must of type <function>');
let t = [...this];
this.length = 0;
for(let e of t) if(callBack(e)) this.push(e);
return this;
}
}
let a = [1,2,3,4,5,5,1,5];
a.filterThis(x=>x!=5);
console.log(a);
Warning: Be very cautious in altering built in prototypes. I would even say unless your making a polyfill don't touch. The errors it can cause can be very subtle and very hard to debug.
Not sure why would you want to do mutation but if you really want to do it, maybe assign it back to itself?
let arr = ['a','b','a'];
arr = arr.filter(x => x !== 'a');
console.log(arr)

Modify an array without mutation

I am trying to solve a problem which states to remove(delete) the smallest number in an array without the order of the elements to the left of the smallest element getting changed . My code is -:
function removeSmallest(numbers){
var x = Math.min.apply(null,numbers);
var y = numbers.indexOf(x);
numbers.splice(y,1);
return numbers;
}
It is strictly given in the instructions not to mutate the original array/list. But I am getting an error stating that you have mutated original array/list .
How do I remove the error?
Listen Do not use SPLICE here. There is great known mistake rookies and expert do when they use splice and slice interchangeably without keeping the effects in mind.
SPLICE will mutate original array while SLICE will shallow copy the original array and return the portion of array upon given conditions.
Here Slice will create a new array
const slicedArray = numbers.slice()
const result = slicedArray.splice(y,1);
and You get the result without mutating original array.
first create a copy of the array using slice, then splice that
function removeSmallest(numbers){
var x = Math.min.apply(null,numbers);
var y = numbers.indexOf(x);
return numbers.slice().splice(y,1);
}
You can create a shallow copy of the array to avoid mutation.
function removeSmallest(numbers){
const newNumbers = [...numbers];
var x = Math.min.apply(null,newNumbers);
var y = newNumbers.indexOf(x);
newNumbers.splice(y,1);
return newNumbers;
}
array.slice() and [... array] will make a shallow copy of your array object.
"shallow" the word says itself.
in my opinion, for copying your array object the solution is:
var array_copy = copy(array);
// copy function
function copy(object) {
var output, value, key;
output = Array.isArray(object) ? [] : {};
for (key in object) {
value = object[key];
output[key] = (typeof value === "object") ? copy(value) : value;
}
return output;
}
Update
Alternative solution is:-
var arr_copy = JSON.parse(JSON.stringify(arr));
I'm not sure what the exact context of the problem is, but the goal might be to learn to write pure transformations of data, rather than to learn how to copy arrays. If this is the case, using splice after making a throwaway copy of the array might not cut it.
An approach that mutates neither the original array nor a copy of it might look like this: determine the index of the minimum element of an array, then return the concatenation of the two sublists to the right and left of that point:
const minIndex = arr =>
arr.reduce(
(p, c, i) => (p === undefined ? i : c < arr[p] ? i : p),
undefined
);
const removeMin = arr => {
const i = minIndex(arr);
return minIndex === undefined
? arr
: [...arr.slice(0, i), ...arr.slice(i + 1)];
};
console.log(removeMin([1, 5, 6, 0, 11]));
Let's focus on how to avoid mutating. (I hope when you say "remove an error" you don't mean "suppress the error message" or something like that)
There are many different methods on Array.prototype and most don't mutate the array but return a new Array as a result. say .map, .slice, .filter, .reduce
Telling the truth just a few mutate (like .splice)
So depending on what your additional requirements are you may find, say .filter useful
let newArray = oldArray.filter(el => el !== minimalElementValue);
or .map
let newArray = oldArray.map(el => el === minimalElementValue? undefined: el);
For sure, they are not equal but both don't mutate the original variable

Cannot get/fetch keys from an array in javascript

I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here

Categories

Resources