I have an array of objects and the property are id and name.
Now I have a function that checks the duplicate value of id and name.
My problem is I make the function redundant. I want to use the code only once to make it as reusable.
The only difference is the property name. Are there any solution to use the function only once? Thanks
var data = [{id: 0, name: "lina"}, {id: 1, name: "jona"}, {id: 2, name: "lina"}, {id: 0},{id: 3, name: "anna"}];
function isDuplicateID() {
for(var i = 0; i < data.length; i++) {
if(data[i].id === 0)
continue;
for(var j = i+1; j < data.length; j++) {
if(data[j].id === data[i].id)
return true;
}
}
return false;
}
function isDuplicateName() {
for(var i = 0; i < data.length; i++) {
if(data[i].name === 0)
continue;
for(var j = i+1; j < data.length; j++) {
if(data[j].name === data[i].name)
return true;
}
}
return false;
}
alert(isDuplicateID())
alert(isDuplicateName())
You can add parameter key and use it. Following code depicts the same
function isDuplicateID(key) {
for(var i = 0; i < data.length; i++) {
if(data[i][key] === 0)
continue;
for(var j = i+1; j < data.length; j++) {
if(data[j][key] === data[i][key])
return true;
}
}
return false;
}
Properties in javascript can be get by either using obj.propName or obj[propName].
var data = [{id: 0, name: "lina"}, {id: 1, name: "jona"}, {id: 2, name: "lina"}, {id: 0},{id: 3, name: "anna"}];
function isDuplicate(propName) {
for (var i = 0; i < data.length; i++) {
if (data[i][propName] === 0)
continue;
for (var j = i + 1; j < data.length; j++) {
if (data[j][propName] === data[i][propName])
return true;
}
}
return false;
}
alert(isDuplicate("id"))
alert(isDuplicate("name"))
Instead of using . to access properties you can enclosed the property name in square brackets, ie instead of . you can use [].
This means you can then pass in the property name, one of the great features of javascript.
function isDuplicate(propertyName) {
for(var i = 0; i < data.length; i++) {
if(data[i][propertyName] === 0)
continue;
for(var j = i+1; j < data.length; j++) {
if(data[j][propertyName] === data[i][propertyName])
return true;
}
}
return false;
}
pass a parameter to your function to choose between the properties:
function isDuplicate(field) {
for(var i = 0; i < data.length; i++) {
if(data[i][field] === 0)
continue;
for(var j = i+1; j < data.length; j++) {
if(data[j][field] === data[i][field])
return true;
}
}
return false;
}
alert(isDuplicate('id'))
alert(isDuplicate('name'))
I'd be inclined to rewrite that function so you only have one loop using indexOf to check for duplicates in a temporary array.
function hasDuplicate(type) {
for (var dupe = [], i = 0, l = data.length; i < l; i++) {
var val = data[i][type];
if (dupe.indexOf(val) > -1) return true;
if (val !== 0) dupe.push(val);
}
return false;
}
hasDuplicate('id');
DEMO
Related
I want to get the sum of the matrix elements, except for those over which the number 0, and get error:
Uncaught TypeError: Cannot set property '0' of undefined
function matrixElementsSum(matrix) {
let s = 0;
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j <= matrix.length; j++) {
if (matrix[i][j] == 0) {
matrix[i+1][j] = 0;
}
s += matrix[i][j]
}
}
return s
}
console.log(matrixElementsSum([[0, 1, 2, 0],
[0, 3, 2, 1],
[2, 0, 2, 3]]))
Your loop counter i should iterate over number of rows and j should iterate over number of columns. Also before setting matrix[i+i][j] to 0, you should also check if i+1 < matrix.length (number of rows)
function matrixElementsSum(matrix) {
let s = 0;
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0 && i+1 < matrix.length) {
matrix[i+1][j] = 0;
}
s += matrix[i][j]
}
}
return s
}
Here is my solution to this problem. Hope it would help someone.
function matrixElementsSum(matrix) {
let susp = [];
return matrix.reduce((t, arr, i)=>{
return arr.reduce((tt, val, ii)=>{
if (val === 0) susp.push(ii);
if (susp.includes(ii)) {
return tt;
} else {
return tt+val;
}
}, 0) + t;
}, 0);
}
Here is my solution with Python:
def solution(matrix):
row_len = len(matrix)
col_len = len(matrix[0])
sum = 0
for c_index in range(col_len):
for r_index in range(row_len):
if matrix[r_index][c_index] == 0:
break
else:
sum += matrix[r_index][c_index]
return sum
function solution(matrix) {
let sum= 0;
for (let i = 0; i < matrix[0].length; i++) {
for (let j = 0; j < matrix.length; j++) {
if (matrix[j][i] === 0) break;
sum+= matrix[j][i];
}
}
return sum;
}
function solution(matrix) {
for(var r=0,j=0;j<matrix[0].length;j++){
for(var i=0;i<matrix.length;i++){
if(matrix[i][j]===0) break
else r+=matrix[i][j]
}
}
return r
}
It took me some time to solve this exercise. I see it was not very complicated.
There is a cycle with the condition how can it be optimized so that the search is faster?
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
for (var k = 0; k < work.length; k++) {
if (db.rows[i].LOGIN === user.rows[j].login && work[k].name === db.rows[i].NAME) {
}
}
}
}
This is typically something that you would expect to see executed on the database.
That being said, you can split up the condition, so that you don't need to perform the second nested loop for every row:
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
if (db.rows[i].LOGIN === user.rows[j].login) {
for (var k = 0; k < work.length; k++) {
if (work[k].name === db.rows[i].NAME) {
}
}
}
}
}
You could take two Maps for the user logins and work names.
var userLogins = new Map(user.rows.map(o => [o.login, o])),
workNames = new Map(o => [o.name, o]),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
If you need just the simple check with using the objects of user.rows or work, you could take a Set instead.
var userLogins = new Set(user.rows.map(({ login } => login)),
workNames = new Set(({ name }) => name),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
Hi I have a problem how to search for words containing at least part of a word. What I mean words that have word I find in array javascript without built-in function except only PUSH.
This task requires no index.of, slice, substr, substring, regex etc. Only PUSH
This my code so far:
function wordsChecker(sentences, search) {
var result = []
for (var i = 0; i < sentences.length; i++) {
var isCheck = false
for (var j = 0; j < sentences.length; j++) {
for (var k = 0; k < search.length; k++) {
if (sentences[i][j] == search[k]) {
isCheck = true
}
}
}
if (isCheck == true) {
result.push(sentences[i])
}
}
return result
}
console.log(wordsChecker(['broom, room, rox, show room, stroom, root, rote, brother'], 'roo'))
//expected output : [broom, room, show room, stroom, root]
Thanks in advance
At the first you should make correct array. I hope this code work for you
function wordsChecker(sentences, search) {
var result = [], k = 0;
for (var i = 0; i < sentences.length; i++) {
var isCheck = false;
for (var j = 0; j < sentences[i].length; j++) {
while (k < search.length) {
if (sentences[i][j] == search[k]) {
isCheck = true;
k++;
break;
}
else {
isCheck = false;
k = 0;
break;
}
}
}
if (isCheck === true && k === search.length) {
result.push(sentences[i]);
k = 0;
}
}
return result;
}
console.log(wordsChecker(['broom', 'room', 'rox', 'show room', 'stroom', 'root', 'rote', 'brother'], 'roo'));
Hi I am developing one jquery application. I am trying to compare the two arrays. For example,
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
Whenever we compare above two arrays I want to return the strings which exists in both arrays or which are common to both arrays!
I tried as below. This piece of code is not working.
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
alert('found ' + SecondArray[j]);
return;
}
}
}
Can anyone help me in this regards! Thank you very much.
You can use indexOf() function
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
var result = new Array();
for (var i = 0; i < Firstarray.length; i++) {
if(SecondArray.indexOf(Firstarray[i])>=0){
result.push(Firstarray[i]);
}
}
console.log(result);
Here is a solution using Array.prototype.filter and Array.prototype.some along with some ES6 flavor thrown in - see demo below:
var firstArray=["Mike","Jack"];
var secondArray=["Mike","Jack","Andy","Cruz"];
var result = secondArray.filter(a => firstArray.some(b => a === b));
console.log(result);
check this How can I find matching values in two arrays?
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
var FirstArray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var commonArray = Array();
var count=0;
for (var i=0; i<FirstArray.length; i++) {
for (var j=0;j< SecondArray.length;j++) {
if (FirstArray[i] == SecondArray[j]){
commonArray[count]=FirstArray[i];
count++;
}
}
}
console.log(commonArray);
Try changing few things in your code :
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
matchedData.push(SecondArray[j]);
}
}
}
alert(matchedData);
working fiddle :
https://jsfiddle.net/o3brcsvw/
try this
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
//alert('found ' + SecondArray[j]);
matchedData.push(SecondArray[j]);
}
}
}
return matchedData;
So that:
array = [[12,13,24],[24,22,11],[11,44,55]]
would return:
cleanedArray = [[12,13,24],[22,11],[44,55]]
I'm surprised not to have found this answered here.
var array = [[12,13,24],[24,22,11],[11,44,55]];
var output = [];
var found = {};
for (var i = 0; i < array.length; i++) {
output.push([]);
for (var j = 0; j < array[i].length; j++) {
if (!found[array[i][j]]) {
found[array[i][j]] = true;
output[i].push(array[i][j]);
}
}
}
console.log(output);
Are you looking for a function that does this for just two-dimensional arrays? If so, then I think this would work:
Array.prototype.clean = function()
{
var found = [];
for(var i = 0; i < this.length; i++)
{
for(var j = 0; j < this[i].length; j++)
{
if(found.indexOf(this[i][j]) != -1)
{
this[i].splice(j, 1);
}
else
{
found.push(this[i][j]);
}
}
}
return this;
};
If it's just a one-dimensional array you're looking for, then:
Array.prototype.clean = function()
{
var found = [];
for(var i = 0; i < this.length; i++)
{
if(found.indexOf(this[i]) != -1)
{
this.splice(i, 1);
}
else
{
found.push(this[i]);
}
}
return this;
};
this would work. If you're doing either of those, then do .clean() on your array to clean it up.
A simple function that modifies the original array is:
function removeDups(a) {
var item, j, found = {};
for (var i=0, iLen=a.length; i<iLen; i++) {
item = a[i];
j=item.length;
while (j--) {
found.hasOwnProperty(item[j])? item.splice(j,1) : found[item[j]] = '';
}
}
return a;
}