I have one array
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
Now I want to check whether "ghi" and "mno" is there or not in array. If there then what is the value.
This is how to do it:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].includes("mno"));
}
Edit, for old browser you can do it this way:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].search("mno"));
}
Where 0 is equal to true ^^
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function valueOf (array, key) {
var value;
if (array.find(function (item) {
return ([ , value ] = item.split("="))[0] === key
})) {
return value;
}
}
console.log(valueOf(arr, "ghi")); // 3
console.log(valueOf(arr, "mno")); // 9
console.log(valueOf(arr, "foo")); // undefined
Using lodash
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
var r = _.find(arr, function(i) { return i.includes('ghi'); });
alert(r);
DEMO
You could use Array.prototype.find() and String.prototype.includes()
arr.find(function(item) {
if(typeof item === "string" && item.includes("asd")) {
return true;
}
return false;
});
Now if an item was found, you can assume that the string was found in the array.
Loop through the array and check each string.
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var pos_of_ghi = searchStringInArray("ghi", arr );
var pos_of_mno = searchStringInArray("mno", arr );
if(pos_of_ghi ==-1){
alert("ghi not found")
}
else{
alert("pos_of_ghi="+pos_of_ghi);
}
if(pos_of_mno ==-1){
alert("mno not found")
}
else{
alert("pos_of_mno="+pos_of_mno);
}
the best and simple logic is:
arr.find(function(item) {
return (typeof item === "string" && item.includes("ghi"));
});
Related
I am trying to remove duplicate JSON Objects from the array in ServiceNow.
Tried below code but it does not remove the duplicate. I want to compare both name & city.
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
alert(splitlen.length);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(uniqueArray.indexOf(splitlen[i].name)==-1)
{
uniqueArray.push(splitlen[i]);
}
}
alert(JSON.stringify(uniqueArray));
Expected output :
[{"name":"Pune","city":"India"}]
uniqueArray.indexOf doesn't work because you're comparing objects against strings (splitlen[i].name). Try to use .find() instead:
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(x => x.name === splitlen[i].name))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
or
var arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
var splitlen = JSON.parse(arr1);
function compare(x){
return x.name === splitlen[i].name;
}
var uniqueArray = [];
var uniqueJson = {};
for(i=0;i<splitlen.length;i++)
{
if(!uniqueArray.find(compare))
{
uniqueArray.push(splitlen[i]);
}
}
console.log(uniqueArray);
you can try this. Also one more thing your array declaration is not right, remove single quotes from array.
var arr1 = [{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}];
function getUniqueListByKey(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
var arr2 = getUniqueListByKey(arr1, "name")
console.log(arr2);
Please try the following example
const arr1 = '[{"name":"Pune","city":"India"},{"name":"Pune","city":"India"}]';
const splitlen = JSON.parse(arr1);
const output = splitlen.reduce((previousValue, currentValue) => {
const { name, city } = currentValue;
const index = previousValue.findIndex(
(entry) => entry.name === name && entry.city === city
);
if (index === -1) {
return [...previousValue, currentValue];
}
return previousValue;
}, []);
console.log(output);
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Put the records in a hashset. If there is collision in the hashset, there is duplicate. This approach is O(n) while comparing all pairs is $O(n^2)$.
I'm trying to get an answer, here's my idea:
Create a function to compare two objects then create a function to get the unique value
function isEquals(obj1, obj2) {
const aProps = Object.getOwnPropertyNames(obj1);
const bProps = Object.getOwnPropertyNames(obj2);
if (aProps.length !== bProps.length) {
return false;
}
for (let j = 0; j < aProps.length; j++) {
const propName = aProps[j];
if (JSON.stringify(obj1[propName]) !== JSON.stringify(obj2[propName])) {
return false;
}
} return true;
}
function getUnique(arr) {
var uniqueArray = [];
for (var item of arr) {
const uniqueItems = arr.filter(i => isEquals(item, i));
if (uniqueItems.length !== 0) {
uniqueArray.push(Object.assign({}, uniqueItems.shift()));
}
arr = arr.filter(i => !isEquals(item, i));
}
return uniqueArray;
}
Hope it helps!
I need to convert a nested array into 2D in javascript, somewhat similar to the question answered for python at link
How to convert 2d nested array into 2d array single?
For example, the array
[[[[[[[[
[16,12],[16,13],[16,14]]
],
[[[[[[
[46,42],[46,43]
]]]]],[
[62,58],[62,59],[62,60]
]]]]]],
[103,102]],[[118,114],[118,115],[118,116]]
]
needs to be converted to
[[16,12],[16,13],[16,14],[46,42],[46,43],[62,58],[62,59],[62,60],[103,102],[118,114],[118,115],[118,116]]
Please help, thanks in advance
This is what I tried, finally works after many trials :
function removeNestArray2D(object) {
var result = [];
if (Array.isArray(object)) { // check if object is valid array
for(var i=0; i<object.length; i++) {
if(!Array.isArray(object[i])) { // check is each of array element is a valid array
return object;
}
else {
var tmp = removeNestArray2D(object[i]);
if(tmp.length == 1) {
result = tmp[0];
}
else if (tmp.length == 2 && Number.isInteger(tmp[0]) && Number.isInteger(tmp[1])) {
result.push(tmp);
}
else {
for (var j=0; j<tmp.length; j++) {
result.push(tmp[j]);
}
}
}
}
}
return result;
}
Recursive approach will help here. Check each array item if there are size 2 and both are number values then push to result array otherwise continue iteration recursively.
const arr = [[[[[[[[
[16,12],[16,13],[16,14]]
],
[[[[[[
[46,42],[46,43]
]]]]],[
[62,58],[62,59],[62,60]
]]]]]],
[103,102]],[[118,114],[118,115],[118,116]]
];
const get2dArray = arr => {
const res = [];
const pushRecursive = arr => {
if (arr.length == 2 && arr.every(x => Number.isInteger(x))) {
res.push(arr);
} else {
arr.forEach(pushRecursive);
}
};
pushRecursive(arr);
return res;
};
console.log(get2dArray(arr));
function removeNestArray2D(object) {
var result = [];
if (Array.isArray(object)) { // check if object is valid array
for(var i=0; i<object.length; i++) {
if(!Array.isArray(object[i])) { // check is each of array element is a valid array
return object;
}
else {
var tmp = removeNestArray2D(object[i]);
if(tmp.length == 1) {
result = tmp[0];
}
else if (tmp.length == 2 && Number.isInteger(tmp[0]) && Number.isInteger(tmp[1])) {
result.push(tmp);
}
else {
for (var j=0; j<tmp.length; j++) {
result.push(tmp[j]);
}
}
}
}
}
return result;
}
This function is able to search for a string in an array:
public checkElement( array ) {
for(var i = 0 ; i< array.length; i++) {
if( array[i] == 'some_string' ) {
return true;
}
}
}
How can i use array of arrays in the for loop? I want to pass this to a function that search a string with if condition.
Example input:
array[['one','two'],['three','four'],['five','six']].
You can try the "find" method instead
let arr = [['one','two'],['three','four'],['five','six']];
function searchInMultiDim(str) {
return arr.find(t => { return t.find(i => i === str)}) && true;
}
searchInMultiDim('one');
This is a recursive solution that checks if an item is an array, and if it is searches it for the string. It can handle multiple levels of nested arrays.
function checkElement(array, str) {
var item;
for (var i = 0; i < array.length; i++) {
item = array[i];
if (item === str || Array.isArray(item) && checkElement(item, str)) {
return true;
}
}
return false;
}
var arr = [['one','two'],['three','four'],['five','six']];
console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false
And the same idea using Array.find():
const checkElement = (array, str) =>
!!array.find((item) =>
Array.isArray(item) ? checkElement(item, str) : item === str
);
const arr = [['one','two'],['three','four'],['five','six']];
console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false
Try this code:
function checkElement(array){
for(value of array){
if(value.includes("some string")){return true}
}
return false
}
console.log(checkElement([["one","two"],["three","four"],["five","six"]]))
console.log(checkElement([["one","two"],["three","four"],["five","some string"]]))
Here is my javascript array:
arr = ['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots'];
With Javascript, how can I count the total number of all unique values in the array that contain the string “dots”. So, for the above array the answer would be 3 (blue-dots, orange-dots, and red-dots).
var count = 0,
arr1 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf('dots') !== -1) {
if (arr1.indexOf(arr[i]) === -1) {
count++;
arr1.push(arr[i]);
}
}
}
you check if a certain element contains 'dots', and if it does, you check if it is already in arr1, if not increment count and add element to arr1.
One way is to store element as key of an object, then get the count of the keys:
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
console.log(Object.keys(arr.reduce(function(o, x) {
if (x.indexOf('dots') != -1) {
o[x] = true;
}
return o
}, {})).length)
Try this something like this:
// Create a custom function
function countDots(array) {
var count = 0;
// Get and store each value, so they are not repeated if present.
var uniq_array = [];
array.forEach(function(value) {
if(uniq_array.indexOf(value) == -1) {
uniq_array.push(value);
// Add one to count if 'dots' word is present.
if(value.indexOf('dots') != -1) {
count += 1;
}
}
});
return count;
}
// This will print '3' on console
console.log( countDots(['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots']) );
From this question, I got the getUnique function.
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
then you can add a function that counts ocurrences of a string inside an array of strings:
function getOcurrencesInStrings(targetString, arrayOfStrings){
var ocurrencesCount = 0;
for(var i = 0, arrayOfStrings.length; i++){
if(arrayOfStrings[i].indexOf(targetString) > -1){
ocurrencesCount++;
}
}
return ocurrencesCount;
}
then you just:
getOcurrencesInStrings('dots', initialArray.getUnique())
This will return the number you want.
It's not the smallest piece of code, but It's highly reusable.
var uniqueHolder = {};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
arr.filter(function(item) {
return item.indexOf('dots') > -1;
})
.forEach(function(item) {
uniqueHolder[item] ? void(0) : uniqueHolder[item] = true;
});
console.log('Count: ' + Object.keys(uniqueHolder).length);
console.log('Values: ' + Object.keys(uniqueHolder));
Try this code,
arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
sample = [];
for (var i = 0; i < arr.length; i++) {
if ((arr[i].indexOf('dots') !== -1) && (sample.indexOf(arr[i]) === -1)){
sample.push(arr[i]);
}
}
alert(sample.length);
var arr = [ "blue-dots", "blue", "red-dots", "orange-dots", "blue-dots" ];
var fArr = []; // Empty array, which could replace arr after the filtering is done.
arr.forEach( function( v ) {
v.indexOf( "dots" ) > -1 && fArr.indexOf( v ) === -1 ? fArr.push( v ) : null;
// Filter if "dots" is in the string, and not already in the other array.
});
// Code for displaying result on page, not necessary to filter arr
document.querySelector( ".before" ).innerHTML = arr.join( ", " );
document.querySelector( ".after" ).innerHTML = fArr.join( ", " );
Before:
<pre class="before">
</pre>
After:
<pre class="after">
</pre>
To put this simply, it will loop through the array, and if dots is in the string, AND it doesn't already exist in fArr, it'll push it into fArr, otherwise it'll do nothing.
I'd separate the operations of string comparison and returning unique items, to make your code easier to test, read, and reuse.
var unique = function(a){
return a.length === 0 ? [] : [a[0]].concat(unique(a.filter(function(x){
return x !== a[0];
})));
};
var has = function(x){
return function(y){
return y.indexOf(x) !== -1;
};
};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
var uniquedots = unique(arr.filter(has('dots')));
console.log(uniquedots);
console.log(uniquedots.length);
I have the following array
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
How can I remove an item from this array using its name or id ?
Thank you
Created a handy function for this..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
countries.results.removeValue('name', 'Albania');
Try this:
var COUNTRY_ID = 'AL';
countries.results =
countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
Try this.(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);
You can delete by 1 or more properties:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}
you can use delete operator to delete property by it's name
delete objectExpression.property
or iterate through the object and find the value you need and delete it:
for(prop in Obj){
if(Obj.hasOwnProperty(prop)){
if(Obj[prop] === 'myValue'){
delete Obj[prop];
}
}
}
This that only requires javascript and appears a little more readable than other answers.
(I assume when you write 'value' you mean 'id')
//your code
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
var c, found=false;
for(c in obj) {
if(obj[c][prop] == val) {
found=true;
break;
}
}
if(found){
delete obj[c];
}
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');
//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');
// print our result to console to check it works !
for(c in countries.results) {
console.log(countries.results[c].id);
}
it worked for me..
countries.results= $.grep(countries.results, function (e) {
if(e.id!= currentID) {
return true;
}
});
You can do it with _.pullAllBy.
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');
// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}
The accepted answer is problematic as it attaches a function to the Array prototype. That function will show up whenever you run thru the array using a for loop:
for (var key in yourArray) {
console.log(yourArray[key]);
}
One of the values that will show up will be the function. The only acceptable way to extend base prototypes (although it is generally discouraged as it pollutes the global space) is to use the .defineProperty method:
Object.defineProperty(Object.prototype, "removeValue", {
value: function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
},
writable: true,
configurable: true,
enumerable: false
});