This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 5 years ago.
I have an array containing objects.
I want to search the array using an if statement for objects that have a certain property and create a separate array containing only those objects.
var firstArray = [...]
for (var a = 0; a < firstArray.length; a++) {
if (firstArray[a].name == 'index.png') {
// create secondArray here
}
}
Thanks for your help!
Just use a filter
var secondArray = firstArray.filter(x => x.name == 'index.png')
var firstArray = [{
'name': 'A'
}, {
'name': 'B'
}, {
'name': 'C'
}]
var newArray = [];
for (name in firstArray) {
if (firstArray[name].name == 'A') {
newArray = firstArray[name];
console.log(newArray)
}
}
Kindly check this snippet.
You can use this way
var obj = {'el1': 1, 'el2': 2};
var firstArray = [{'el1': 1, 'el2': 2}, {'el3': 1, 'el4': 2}]
var searchTerm = 'el1';
for(var a=0; a<firstArray.length; a++){
for(var key in firstArray[a]){
if(key == searchTerm){
// do whatever you want to do.
console.log('key = ', key, 'value = ', obj[key]);
}
}
}
Related
This question already has answers here:
Create objects dynamically out of a dot notation like string
(6 answers)
Closed 1 year ago.
I am trying to convert the following array into an object:
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
So it will look like this:
var targetObject = {
car: {
name: '',
age: '',
event: {
id: ''
}
}
,
zz: {
yy: {
dd: {
aa: ''
}
}
},
aa: {
yy: {
zz: {
dd: {
kk: '',
}
}
}
}
}
This is my code:
targetObject = {}
function arrayToObject(arr){
//iterate through array and split into items
for (var i = 0; i < arr.length; ++i){
var item = arr[i].split(".");
//iterate through item that has just been splitted
for (var u = 0; u < item.length; ++u){
//if item is not in targetobject create new object
if(!(item[0] in targetObject)){
targetObject[item[0]] = {}
} else {
//else go into the object and add the item/property to the existing object
targetObject[item[0]][item[u]] = {}
}
}
}
console.log(targetObject);
}
arrayToObject(arr);
It outputs only in second level and i can't figure out to do it with the several levels. I know the code is oldschool, so I would also really like to know how this can be done easier.
You could use forEach to loop over array and then split with reduce to build nested object.
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
const result = {}
arr.forEach(str => {
str.split('.').reduce((r, e, i, a) => {
return r[e] = (r[e] || (a[i + 1] ? {} : ''))
}, result)
})
console.log(result)
Or with your approach with for loops you just need to keep some reference and update the current nested object, so you could do it like this.
var arr = [
'car.name',
'car.age',
'car.event.id',
'zz.yy.dd.aa',
'aa.yy.zz.dd.kk'
];
const targetObject = {}
let ref = targetObject;
function arrayToObject(arr) {
//iterate through array and split into items
for (var i = 0; i < arr.length; ++i) {
var item = arr[i].split(".");
//iterate through item that has just been splitted
for (var u = 0; u < item.length; ++u) {
const last = u == item.length - 1
const str = item[u]
if (!ref[str]) {
ref[str] = (last ? '' : {})
}
ref = ref[str]
if (last) {
ref = targetObject;
}
}
}
}
arrayToObject(arr);
console.log(targetObject)
This question already has answers here:
Completely removing duplicate items from an array
(11 answers)
Closed 1 year ago.
In this case I have 3 arrays in javascript:
var array1 = ['124','10','100','190','1000'];
var array2 = ['124','100','190', '45'];
var array3 = ['124','100','175','19','1900'];
I need a script that get the unique values from 3 or more arrays (in this case 3 arrays). the result should be:
['10','1000','45','175','19','1900']
Thanks for the help
You could take a Map and set known keys to value false and vice versa.
Then map the map, filter and map only the keys.
In pieces:
Make a single array with all values from the arrays with spread syntax ....
Reduce the array wih a Map and set unseen values to true and seen values to false. The result ia a map with all values as key and as value either true or false, depending on uniqueness or not.
By having a map, you need to take only the keys with a value true. This requires an array from the map.
Filter the array to get only unique keys.
Map the array to get only the key.
The result is an array with unique values.
const
a = ['124', '10', '100', '190', '1000'],
b = ['124', '100', '190', '45'],
c = ['124', '100', '175', '19', '1900'],
unique = Array
.from([...a, ...b, ...c].reduce((m, v) => m.set(v, !m.has(v)), new Map))
.filter(([, b]) => b)
.map(([v]) => v);
console.log(unique);
This is quite elegant solution to this problem. It looks for global unique values even in the same array.
var array1 = ['124','10','100','190','1000'];
var array2 = ['124','100','190', '45'];
var array3 = ['124','100','175','19','1900'];
function getUniqueValues(...arrays) {
const concatetedArray = arrays.flat();
return arrays.reduce((accumulator, current) => {
return [...accumulator, ...current.filter((currentItem) => concatetedArray.indexOf(currentItem) === concatetedArray.lastIndexOf(currentItem))];
}, [])
}
console.log(getUniqueValues(array1, array2, array3));
A solution is to use an object like this:
var array1 = ['124', '10', '100', '190', '1000'];
var array2 = ['124', '100', '190', '45'];
var array3 = ['124', '100', '175', '19', '1900'];
const obj = {};
for (let i = 0; i < array1.length; i++) {
if (!obj[array1[i]]) {
obj[array1[i]] = 0;
}
obj[array1[i]]++;
}
for (let i = 0; i < array2.length; i++) {
if (!obj[array2[i]]) {
obj[array2[i]] = 0;
}
obj[array2[i]]++;
}
for (let i = 0; i < array3.length; i++) {
if (!obj[array3[i]]) {
obj[array3[i]] = 0;
}
obj[array3[i]]++;
}
const uniques = [];
Object.keys(obj).forEach(key => {
if (obj[key] == 1) {
uniques.push(key);
}
})
console.log(uniques);
This question already has answers here:
Count unique elements in array without sorting
(9 answers)
Closed 6 years ago.
Okay I researched this one and couldn't find an answer here so hopefully this isn't a duplicate. I'm also trying not to be specific in order to figure this out on my own.
var arr = ['cat','car','cat','dog','car','dog']
function orgNums(input) {
var count = 0;
var obj = {};
for (var i = 0; i < input.length; i++) {
if (input[i] === 'cat')
obj['cat'] = count++;
}
return obj;
}
I want it to return {cat:2} but I'm getting {cat:1}
Eventually I want it to return {cat:2, car:1, dog:2, gerbil:1}
So I tried using obj[cat] = ++count and I'm getting the answer I want, but when I try a second if statement: if input[i] === 'dog', obj[dog] = ++countI get {cat:2, dog:4}. I noticed that it's taking what count already is at, 0, then moves it to 2 to count cat, then moves it to 4, taking the dog count of 2 and adding 2 to it. How do I prevent that from happening so that count restarts at 0 each time?
EDIT:
So this works beautifully
var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']
function orgNums(input) {
var obj = {};
for (var i = 0; i < input.length; i++) {
obj[input[i]] = obj[input[i]] || 0;
obj[input[i]]++;
}
return obj;
}
console.log(orgNums(arr));
but the final output i actually want is:
[
{cat:1
dog:2
}
{car:2
}
]
So I tried throwing in an if statement like this:
if (input[i] === 'cat'||'dog')
but it's still throwing car into the object. I'll try to figure out the multiple objects in the array. Thanks again!
You could just reduce the array, and count the keys as you go
var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog', 'horse'];
function orgNums(input) {
return input.reduce((a, b) => {
return b in a ? a[b]++ : a[b] = 1, a;
}, {});
}
console.log(orgNums(arr));
The assignment of count, which is used in the loop, does not work in this case, because of the postfix increment count++. This gives you the value of the counter and increment later, If you take the prefix increment ++count, you get the incremented value assigned.
// Postfix
var x = 3;
y = x++; // y = 3, x = 4
// Prefix
var a = 2;
b = ++a; // a = 3, b = 3
But you can omit the variable and count directly with a property of the object. for all items in one loop.
You could use the element as key for the object. Then assign with zero, if not exist and increment.
var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']
function orgNums(input) {
var obj = {};
for (var i = 0; i < input.length; i++) {
obj[input[i]] = obj[input[i]] || 0;
obj[input[i]]++;
}
return obj;
}
console.log(orgNums(arr));
A more compact version of the above with Array#forEach
var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']
function orgNums(input) {
var obj = {};
input.forEach(function (item) {
obj[item] = (obj[item] || 0) + 1;
});
return obj;
}
console.log(orgNums(arr));
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?
This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.
I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}
var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete from array in javascript
I have the following JSON object:
[id:84,id:92,id:123,id:2353]
How would I go about removing the item which the value is "123" using javascript?
or if I formatted the json as
[84, 92, 123, 2353]
How would it be removed in this case?
Assume you have this:
var items = [{ id: 84 }, { id: 92 }, { id: 123 }, { id: 2353 }];
var filtered = items.filter(function(item) {
return item.id !== 123;
});
//filtered => [{ id: 84 }, { id: 92 }, { id: 2353 }]
Supposing you actually have an object from a json in the json variable
for (key in json) {
if (json.hasOwnProperty(key) && json[key] == 123) {
delete json[key];
}
}
Shorter alternative would be:
var newArr = [{id:84}, {id:92}, {id:123}, {id:2353}].filter(function(a) {
return a.id != 123;
});
If you have this:
var arr = [{id:84}, {id:92}, {id:123}, {id:2353}]
To remove the item with value 123, you can do:
for(var i = 0; i < arr.length; i++) {
if(arr[i].id == 123) {
arr.splice(i, 1);
break;
}
}
function removeClass(obj, cls) {
var classes = obj.className.split(' ');
for(i=0; i<classes.length; i++) {
if (classes[i] == cls) {
classes.splice(i, 1);
i--; // (*)
}
}
obj.className = classes.join(' ');
}
var obj = { className: 'open menu menu' }
removeClass(obj, 'menu')
alert(obj.className)
You can use splice function, like this:
var data = [{id:84}, {id:92}, {id:123}, {id:2353}];
function remove(){
for(var i = 0, max = data.length; i < max; i++) {
var a = data[i];
if(a.id === 123) {
data.splice(i, 1);
break;
}
}
}
remove();
Seems like you want to avoid a loop. Assuming it's available, you can use .filter:
[{id:84},{id:92},{id:123},{id:2353}]
.filter(function (elem) { return elem.id !== 123; });
This technically does do a loop, but at least you don't have to look at it.
Assuming your "json" is really an array, like [84, 92, 123, 2353]:
var myString = "[84, 92, 123, 2353]";
var myArray = JSON.parse(myString);
var index = myArray.indexOf(123); // whatever value you are looking for
myArray.splice(index, 1);
http://jsfiddle.net/7vkK6/
Assuming I'm understanding your question and comments correctly you can do something like this:
var old_array = [{id: 84},...];
var new_array = [];
for(var i = 0, len = old_array.length; i++) {
if (old_array[i].id != 123) new_array.push(old_array[i]);
}
What you have currently is not JSON so I'll give you some different options.
If you have an Array arr = [84,92,123,2353] then
arr = arr.filter(function (x) {return x !== 123;}); // all occurrences
// OR
arr.splice(arr.indexOf(123), 1); // first occurrence only
If you have an Object obj = {"84": a, "92": b, "123": c, "2353": d}, a to d some expressions, then
delete obj['123']; // obj now {"84": a, "92": b, "2353": d}
1) JSON is a string, not an array or an object.
var json = "[1,2,3]";
2) Valid JSON NEEDS to be valid JS
var myJSObj = { 1,2,3 }, // broken
myJSArr = [ name : 1, name2 : 2 ]; // broken
3) If you have a JS Array, you can remove an element by using [].splice
var arr = [ 1, 2, 3, 4 ],
i = 0, l = arr.length,
test = 4;
for (; i < l; i += 1) {
if (arr[i] === test) { arr.splice(i, 1); } // remove 1 starting at i
}
4) If you have an object with named keys, you can use delete
var obj = { val : 1 };
delete obj.val;